How to read up to special character from input file

Hi, I want to read and print out special character from a file. The input file looks likes this:

Acrux~Alpha 1 Crucis~HR 4730~HD 108248~320.00
Achird~Eta Cassiopeiae~HR 219~HD 4614~19.41
Ain Al Rami~Nu 1 Sagittarii~HR 7116~HD 174974~1850.59

I want to look up "Alpha 1 Crucis, Eta Cassiopeiae, Nu 1 Sagittarii" from the file which is after "~". These are basically starProperName. I will ask the user for starProperName and then print the whole line of it. For example the user asks for Alpha 1 Crucis so I will be showing him Acrux~Alpha 1 Crucis~HR 4730~HD 108248~320.00
How do I do that? Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   if (fin.fail())
    {
        cout << "The file name " << "\"" << fileName <<"\"" << " does not exist "<< endl;
        return 0;
    }
    else
    {
       string starProperName;
       cout << "Enter star proper name >> ";
       cin >> starProperName;
    }
    fin.close();
}
Last edited on
You could read in every line in turn into a string, and then use string::find function to search it for what the user is looking for, and if it's in the line, output the line and finish.
It is only reading the first word when I write "Alpha 1 Crucis". and displaying all the results that include Alpha in it. How can I ask it to show me results that include the whole word. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
else
    {
       string starProperName;
       cout << "Enter star proper name >> ";
       cin >> starProperName;

       while (std::getline(fin, line))
       {

          std::size_t i = line.find(starProperName);
          if (i != std::string::npos)
          {
             std::cout << line << "\n";
          }
          else
          {
             cout << "No star with the proper name " << "\"" << starProperName << "\"" << " was found " << endl;

          }
       }
    }
    fin.close();
Use getline for the input from the user.

https://en.cppreference.com/w/cpp/string/basic_string/getline
Topic archived. No new replies allowed.