2017-07-26 17 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; 
相关问题