Using c-strings.

Apr 30, 2015 at 1:16pm
How can you read from a file a line of words (sentence) using c-strings? Let's say you have a character array and then inside a text file is a group of sentences:

I like playing video games.
I love programming.
C++ is awesome!

I'm trying to read from the file and insert each of the sentences inside a character array. How would you go about doing that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> 
#include <fstream> 

using namespace std; 

 int main() 
{
  ifstream inFile.open("sentence.txt"); 

  char str[100]; 
  inFile >> str //??????
  return 0; 
}
Apr 30, 2015 at 2:26pm
You will be better off to read each line in a loop: Take a look at getline.
Apr 30, 2015 at 3:35pm
Thanks for the reply! But I've already used getline before. I was just wondering if there is a way to input a group of words (with spaces) into a c-string. Would you have to concatenate each individual word or string?
Apr 30, 2015 at 5:02pm
Well, it depends on your input: If you have a file with words delimited by spaces, and several words on each line, it makes sense to read them in as an entire line. The getline() function does just that. You should use a standard container instead of character arrays: They are much easier and automatically allocate the memory needed for your data:

See this linke: http://www.cplusplus.com/reference/string/string/getline/
Topic archived. No new replies allowed.