Reading the first character of a line from a text file

I have a text file like this:

0 user1
1 user2
2 user3
3 user4
4 user5

If the first line of the string is equal to 0 or 1, etc. I want to do something with it.

So I need code that finds the character at position 0 of the line.

The code below is what I tried but it doesn't work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   DataIn.open("Data.txt", ios::in);

    while (DataIn >> text)
        {

        cout << text.at(0);



        }
    
   DataIn.close();

Last edited on
So I need code that finds the character at position 0 of the line.
Are you sure that's what you want?
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <fstream>
#include <string>
int main()
{
  std::ofstream data_in{"my_text_file.txt"};
  for (std::string line; std::getline(data_in, line); )
    if (line.size()) 
      std::cout << line[0] << '\n'; 
}
Last edited on
Yes that works, thank you.

Registered users can post here. Sign in or register to post.