0

I'm trying to read from a file using file.get() but it seems to be stuck in the first line. Input file is like:

1234,56
7891,01
.......

This is my code:

char* n1 = new char[5];
char* n2 = new char[3];
std::ifstream data("input_file");
while (i < 4) {
    data.get(n1, 5);
    printf("%ld\n", data.gcount());
    data.get(n2, 3);
    printf("%ld\n", data.gcount());
    //read newline
    data.get(&ch, 2);
    printf("%ld\n", data.gcount());
    printf("n1= %s, n2 = %s\n", n1, n2+1);
}

Output:

0
0
0
n1= 1234, n2 = 56
0
0
0
n1= 1234, n2 = 56
0
0
0
n1= 1234, n2 = 56

I'm not able to make any sense of this.

4

2 回答 2

0

这里有一个问题:

data.get(&ch, 2);

假设您ch之前在某处定义为

char ch;

换行符将被存储在,ch但终止符'\0'将被写入到 之后的下一个地址ch,从而破坏发生在那里的任何变量。

将其更改为:

char ch[2];

data.get(ch, 2);
于 2013-05-14T15:39:19.733 回答
0

get(char*, streamsize) 一遇到换行符就会卡住。您需要使用 getline() 前进到下一行。

此外,您的第二个 get() 仅从流中读取 2 个字符(即您将在第一行读取“,5”而不是“,56”。

于 2013-05-14T16:06:45.487 回答