-1

How do I access individual elements of a line read from a file?

I used the following to read a line from a file:

getline(infile, data) // where infile is an object of ifstream and data is the variable where the line will be stored

The following line is stored in data : "The quick brown fox jumped over the lazy dog"

How do I access particular elements of the line now? What if I want to play around with the second element ( quick ) of the line or get hold of a certain word in the line? How do I select it?

Any help will be appreciated

  • Which version of `getline` are you using? That is, is `data` a `string` or a `char[]`? And do you want to learn fundamentals by iterating around in the container yourself, or learn a high-level tool like `stringstream`? – Beta Aug 30 '20 at 14:59
  • @Beta data is a string. I just want to find a simple solution that can just store each element of the line in a variable. – prestonphilly Aug 30 '20 at 15:08
  • You can split the line (as a string) on space into a vector of string objects, then manipulate the items in the vector. – Eljay Aug 30 '20 at 15:17
  • Does this answer your question? [How do I iterate over the words of a string?](https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string) – puio Aug 30 '20 at 19:12

2 Answers2

2

data = "The quick brown fox jumped over the lazy dog" and the data is string , your string delimeter is " ",you can use std::string::find() to find the position of the string delimeter and std::string::substr() to get a token:

std::string data = "The quick brown fox jumped over the lazy dog";
std::string delimiter = " ";
std::string token = data.substr(0, data.find(delimiter)); // token is "the"
Asocia
  • 5,935
  • 2
  • 21
  • 46
1

Since your text is space separated, you can use std::istringstream to separate the words.

std::vector<std::string> words;
const std::string data = "The quick brown fox jumped over the lazy dog";
std::string w;
std::istringstream text_stream(data);
while (text_stream >> w)
{
    words.push_back(w);
    std::cout << w << "\n";
}

The operator>> will read characters into a string until a space is found.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154