Using getline for multiple cstrings?
Nov 14, 2013 at 12:51am UTC
I'm trying to extract lines from a text file. Because multiple lines make up one "set" of data, I need to have multiple variables to represent each line for processing's sake. Here's my simplified code of the problem:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char name[31];
char address[81];
ifstream inFile;
//open file
inFile.open("file.txt" );
inFile.getline(name, 31, '/n' );
cout << "Name is " << name << endl;
inFile.getline(address, 81, '/n' );
cout << "Address is " << address << endl;
return 0;
}
When I run the code above, I get
1 2
Name is John Smith
Address is
file.txt contains the following lines:
1 2 3 4 5
John Smith
101 Main Street
Bilbo Baggins
55 Hobbiton Road
//and so on
It seems like it's never going to the next line. What can I do about this?
Last edited on Nov 14, 2013 at 12:52am UTC
Nov 14, 2013 at 3:14am UTC
occur this result,because in the file.txt,you use the spaces between John smith and 101 Main Street instead of the newline.
Nov 14, 2013 at 3:35am UTC
This:
inFile.getline(name, 31, '/n' );
The newline character is '\n'
, not '/n'
.
Maybe that's why it's acting weird for you.
Topic archived. No new replies allowed.