2017-07-26 37 views
0

我一直在努力處理這個bug一段時間。我使用windows 10和code :: blocks 16.01 MinGW。字符不一致的迴應 n

我想比較c到結束行字符。我的系統上

一個程序成功運行,只是跳過的文件的標題行:

while(c!='\n') 
{ 
    c = fgetc(traverse); 
    if(c == EOF) 
     return(1); 
} 

其中橫向使用

fopen("traverse.dat", "r"); 
然而

開了,我的其他程序:

FILE * infile; 

/* Open a large CSV */ 
infile = fopen("Getty_Megatem.csv", "r"); 
if(infile == NULL) 
{ 
    printf("no file"); 
    return(EXIT_FAILURE); 
} 
char c = 0; 
int i = 0; 

/* Opens file successfully */ 
printf("File opened\n"); 

/* Count commas in first line */ 
while(c != '\n'); 
{ 
    c = fgetc(infile); 
    if(c == ',') 
     i++; 
    if(c == EOF) 
     return(EXIT_FAILURE); 
} 

printf("Number of commas: %i\n", i); 

fclose(infile); 

return(EXIT_SUCCESS); 

and

ifstream infile; 
char c; 
string mystr; 

infile.open("ostring.dat"); 

// Skip a line 
while (c!= '\n') 
    infile >> c; 

getline(infile, mystr); 

和(一個我真的想工作)

ifstream emdata; 

string firstline; 
char c = 0; 
int i = 0; 

vector<double> vdata; 

// redundancy 
vdata.reserve(10000); 

// There are ~ 300 doubles per line 
emdata.open("Getty_Megatem.csv"); 

// Skip first line 
getline(emdata, firstline); 

while(c != '\n' && c != EOF) 
{ 
    emdata >> vdata[i] >> c; 
    cout << vdata[i] << ","; 
    i++; 

    if(i == 999) 
    { 
     cout << "\n\ni>9999"; 
     break; 
    } 
} 


emdata.close(); 
return 0; 

是不成功的,他們編譯和執行,然後永遠地讀取流 - 或者直到我最大迭代9999爲止。所有這些文件都包含新行。

+0

的投入,我不明白爲什麼你不只是'函數getline()'每行? –

+0

我想將行讀入雙向量 – Edward

+3

您的C變體有這樣一行:'while(c!='\ n');'末尾有一個分號,它被解釋爲空語句。實際上,這說:「c'不是一個換行符,這將永遠是真的。刪除該分號。 –

回答

1

您正在使用格式化輸入時,你應該使用格式化輸入進入一個人物:

char c; 
if (cin.get(c)) ... 

int c; 
c = cin.get(); 
if (c != cin.eof()) ... 

>>運營商刪除空格,換行包括。

0

正如評論中指出的,第一個不會工作,因爲它有一個; ()之後。 另外兩個問題是>>操作符不會讀取'\ n'和空格,它們被視爲分隔符。這就是爲什麼最後兩個不起作用。

要修正第一個剛刪除的; while語句後

//while(c != '\n'); 
while(c != '\n') 
{ 
    c = fgetc(infile); 
    if(c == ',') 
     i++; 
    if(c == EOF) 
     return(EXIT_FAILURE); 
} 

這裏是我的建議,爲他人:

2日 - 忘了一段時間,如果你想跳過一條線,讓線,什麼也不做它。

ifstream infile; 
char c; 
string mystr; 

infile.open("ostring.dat"); 

// Skip a line 
getline(infile, mystr); 
/*while (c!= '\n') 
    infile >> c;*/ 

getline(infile, mystr); 

3日 - 讓行並使用字符串流,以獲得您所需要

ifstream emdata; 

string firstline; 
char c = 0; 
int i = 0; 

vector<double> vdata; 

// redundancy 
vdata.reserve(10000); 

// There are ~ 300 doubles per line 
emdata.open("Getty_Megatem.csv"); 

// Skip first line 
getline(emdata, firstline); 
//get second line 
getline(emdata, firstline); 
// replace commas with spaces 
std::replace(firstline.begin(),firstline.end(),',',' '); 
stringstream ss(firstline);// 
while(ss.rdbuf()->in_avail()!=0)//loop until buffer is empty 
{ 
    ss >> vdata[i]; 
    cout << vdata[i] << ","; 
    i++; 

    if(i == 999) 
    { 
     cout << "\n\ni>9999"; 
     break; 
    } 
} 


emdata.close(); 
return 0;