Reputation: 3245
When I run this code in visual studio I get the right output: The correct output looks like:
But when I run the same code in hopper (unix) I am getting some weird output.. it looks like this:
the code is below:
//#include <mysql.h>
#include <iomanip>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <conio.h>
using namespace std;
int main()
{
//connect= mysql_init(&mysql);
//connect= mysql_real_connect(&mysql,SERVER,USER,PASSWORD,DATABASE,0,0,0);
cout<<endl;
ifstream inFile;
ofstream outFile;
inFile.open("team.txt");
if (inFile.fail())
{
cout<<" ***ERROR*** File not found ***ERROR*** "<<endl;
//exit(1);
}
else
{
string sqlQuery2;
int numOfLines=0;
while(!inFile.eof())
{
numOfLines++;
string line;
getline(inFile,line) ;
int y = line.length();
string nums,city,conf,name;
int count=0;
for(int x=0;x<y;x++)
{
if(line[x]!=':' && count==0)
{
nums+=line[x];
}
else if(line[x]!=':' && count==1)
{
city+=line[x];
}
else if(line[x]!=':' && count==2)
{
conf+=line[x];
}
else if(line[x]!=':' && count==3)
{
name+=line[x];
}
else if (line[x]==':')
{
count++;
}
}
sqlQuery2="INSERT INTO team VALUES ("+nums+",'"+city+"','"+conf+"','"+name+"');";
cout<<sqlQuery2<<endl;
//mysql_query(connect,sqlQuery2.c_str());
}
}
inFile.close();
_getch();
return 0;
}
Upvotes: 3
Views: 62
Reputation: 206717
I think the problem is that your input file, team.txt, was created in a Windows machine. It has DOS-style line endings.
If you add a check
else if (line[x]=='\r')
{
// Ignore the character
}
your output should be OK on a non-Windows machine.
Suggestion for improvement
Use of
while(!inFile.eof())
{
is fraught with problems. See Why is iostream::eof inside a loop condition considered wrong? for more details.
Replace the block:
while(!inFile.eof())
{
numOfLines++;
string line;
getline(inFile,line) ;
by
string line;
while(getline(inFile,line))
{
numOfLines++;
Upvotes: 2
Reputation: 8514
It looks like you have run afoul of line endings. In windows lines end in \r\n
("carriage return", "line-feed"), in Unix, they just have \n
.
This means that the end of the line
string, you have a carriage return.
Your code is currently putting this carriage return into the name
variable and then adding it into the sqlQuery2
string. When you output the value, the carriage return character moves the cursor to the start of the current line and starts overwriting the output.
One solution is to fix your data file. You can use the the dos2unix utility for that, or there are a number of other ways. See this SO post enter link description here for more info. You could also possibly change the way you are putting it onto your unix system, (ftp can change it automatically).
If you don't want to do that you could add code to look for \r
in your line
string and ignore it.
Upvotes: 2