按字符不一致的字符\ n

时间:2017-07-26 18:05:20

标签: c++ windows newline codeblocks

我一直在努力解决这个问题。我使用的是Windows 10和code :: blocks 16.01 MinGW。

我想将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);

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。所有这些文件都包含新行。

2 个答案:

答案 0 :(得分:1)

当您使用无格式输入时,您正在使用格式化输入来获取字符:

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

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

>>运算符会删除空格,包括换行符。

答案 1 :(得分:0)

正如评论中指出的那样,第一个不会起作用,因为它有一个;就在while()之后。 另外两个问题是&gt;&gt;运算符不读取'\ n'和空格,它们被视为分隔符。这就是为什么最后两个不起作用的原因。

修复第1只是删除;在while语句之后

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

以下是我对其他人的建议:

第二 - 忘了一会儿,如果你想跳过一条线,就行了,不做任何事。

ifstream infile;
char c;
string mystr;

infile.open("ostring.dat");

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

getline(infile, mystr);

3rd - 获取该行并使用stringstream获取所需的输入

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;