getline function weird errors
I was trying do some file read/write stuff and I am unable to run my second getline command. Any ideas as to why this happens?
char str[80];
char substr[10];
file.open("abc.txt", fstream::in);
file.getline(str,'\n');
while(!file.eof())
{
i=0;
while(str[i]!='\n') {substr[i] = str[i++]; }
substr[i++]='\n';
cout<<substr;
file.getline(str,'\n');
}
abc.txt
AND 1 2 3
NAND 4 5 6
NOR 2 3 7
XOR 1 6 8
OR 8 7 9
开发者_JAVA百科I used notepad++ to create the txt file, so am pretty sure there are CR/LF at the end of each line
2nd argument of fstream::getline
is the streamsize, not delimiter. For delimited version, you need the overloaded version. See this reference.
Following up with my comment, try moving the file.getline command within the while loop:
...
while(!file.eof())
{
file.getline(str,80,'\n');
...
This works. Use getline() in the while condition and get the string delimeted by '\n' and use strcpy.
char str[80] = { '\0' };
char substr[80] = { '\0' };
ifstream file;
file.open("abc.txt", fstream::in);
int i = 0;
while(file.getline(str, 79, '\n'))
{
strncpy(substr, str, 78);
substr[strlen(substr)]='\n';
cout<<substr;
}
精彩评论