[英]I am having trouble debugging the code below. I am getting correct output in visual studio,
當我在visual studio中運行此代碼時,我得到了正確的輸出:正確的輸出如下:
但是當我在hopper(unix)中運行相同的代碼時,我得到一些奇怪的輸出..它看起來像這樣:
代碼如下:
//#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;
}
我認為問題是你的輸入文件team.txt是在Windows機器上創建的。 它有DOS風格的行結尾。
如果您添加支票
else if (line[x]=='\r')
{
// Ignore the character
}
您的輸出應該在非Windows機器上正常。
建議改進
用於
while(!inFile.eof())
{
充滿了問題。 請參閱為什么循環條件中的iostream :: eof被認為是錯誤的? 更多細節。
替換塊:
while(!inFile.eof())
{
numOfLines++;
string line;
getline(inFile,line) ;
通過
string line;
while(getline(inFile,line))
{
numOfLines++;
看起來你已經與行結尾發生了沖突。 在windows行中以\\r\\n
結尾(“回車”,“換行”),在Unix中,它們只有\\n
。
這意味着line
字符串的結尾,你有一個回車符。
您的代碼當前將此回車符放入name
變量,然后將其添加到sqlQuery2
字符串中。 當您輸出該值時,回車符將光標移動到當前行的開頭並開始覆蓋輸出。
一種解決方案是修復您的數據文件。 您可以使用dos2unix實用程序,或者有許多其他方法。 有關詳細信息,請參閱此SO帖子在此處輸入鏈接說明 。 你也可以改變你把它放到你的unix系統上的方式,(ftp可以自動改變它)。
如果您不想這樣做,可以添加代碼以line
字符串中查找\\r
並忽略它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.