reading from a text file
-
Hi, I have some code which loads a char[] into memory from the source txt file, Example ifstream inn; char text[20]; char text2[10]; inn.open("test.txt"); inn >> text; inn >> text2; cout << text; cout << text2; inn.close(); the text file contains test and test test My problem is that this code only loads each word, seperated by a space in order. I want it to load it in order based on a new line. Any ideas?, thanks Fred
-
Hi, I have some code which loads a char[] into memory from the source txt file, Example ifstream inn; char text[20]; char text2[10]; inn.open("test.txt"); inn >> text; inn >> text2; cout << text; cout << text2; inn.close(); the text file contains test and test test My problem is that this code only loads each word, seperated by a space in order. I want it to load it in order based on a new line. Any ideas?, thanks Fred
FredrickNorge wrote:
My problem is that this code only loads each word, seperated by a space in order. I want it to load it in order based on a new line.
The
opeartor>>
will stop when it gets to any whitespace. To get an entire line, usegetline
instead.ifstream inn; char text[20] = {0}; char text2[10] = {0}; inn.open("test.txt"); inn.getline(text, 19); inn.getline(text2, 19); cout << text; cout << text2; inn.close();
Alternatively, you can use another version of getline that takes a string argument:
ifstream inn; string text = ""; string text2 = ""; inn.open("test.txt"); getline(inn, text); getline(inn, text2); cout << text.c_str(); cout << text2.c_str(); inn.close();
If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac
-
FredrickNorge wrote:
My problem is that this code only loads each word, seperated by a space in order. I want it to load it in order based on a new line.
The
opeartor>>
will stop when it gets to any whitespace. To get an entire line, usegetline
instead.ifstream inn; char text[20] = {0}; char text2[10] = {0}; inn.open("test.txt"); inn.getline(text, 19); inn.getline(text2, 19); cout << text; cout << text2; inn.close();
Alternatively, you can use another version of getline that takes a string argument:
ifstream inn; string text = ""; string text2 = ""; inn.open("test.txt"); getline(inn, text); getline(inn, text2); cout << text.c_str(); cout << text2.c_str(); inn.close();
If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac
thanks!, exactly what i needed. Fred