-1

Here is first line of my file: Mr Blake Brown 1234

struct Data
{
  string name;
  int number;
}

Data t[n];
for(int i=0; i < n; i++) 
{ 
  t[i].name = (Mr Blake Brown)
  t[i].number = (1234)
}

How can I read the line correctly? If I want to put the hole name (Mr Blake Brown) into t[i].name?

Awarestor
  • 25
  • 7
  • Does this answer your question? [Read file line by line using ifstream in C++](https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c) This topic answers on your question: [2. Line-based parsing, using string streams](https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c) – 273K Apr 19 '20 at 20:50
  • 5
    You can [read the whole line](https://en.cppreference.com/w/cpp/string/basic_string/getline) into a string, then do a [reverse find](https://en.cppreference.com/w/cpp/string/basic_string/rfind) of the last space and split into two [substrings](https://en.cppreference.com/w/cpp/string/basic_string/substr), and finally [convert the numeric string into an `int`](https://en.cppreference.com/w/cpp/string/basic_string/stol). – Some programmer dude Apr 19 '20 at 20:50

1 Answers1

0

I will assume you want to read from the console and you already have iostream included because your question is ambiguous. If you want to read a single string without spaces use the below method:

struct Data
{
  string name;
  int number;
};

int main()
{
    Data t[n];
    for(int i=0; i < n; i++) 
    { 
      std::cin >> t[i].name;
      std::cin >> t[i].number;
    }
}

This will retrieve the a single string from the console. Also your struct needs a semicolon after the ending curly bracket.

In the case that you want the full line with spaces, you could use:

getline();

This will retrieve the full line from any file or the console. Refer to the documentation for the full details here.

Clu3l3ss
  • 23
  • 1
  • 7