How to stop user input by typing a specific string?

Hi everyone! I am having issues with how to terminate an input stream with a specific pre-defined string instead of a generic Ctrl+Z. Here is my code (INCOMPLETE!):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <complex>
#include <ctime>

using namespace std;

int main()
{
    cout << "Please type a person's name and his/her score." << endl;
    string name;
    int score;
    int x = 0;
    vector<string>names;
    vector<int>scores;
    
    // How should I terminate the input stream below with a "No more" string instead of a generic Ctrl+Z ? Thank you!
    
    while(cin >> name >> score)
    {
        for(int i = 0; i <=x; i++)
        {
            if(name == names[i])
            {
                cout << "Sorry. The name: " << name << " is entered twice." << endl;
                cout << "Please type a person's name and his/her score." << endl;
            }
            else{
            names.push_back(name);
        scores.push_back(score);
        cout << "Please type a person's name and his/her score." << endl;
        x++;}
        
        }
        
    }
    
    cout << "Program terminated by user." << endl;
    for(int y = 0; y <= x; y++)
    {
        cout << names[y] << " --- " << scores[y] << endl;
    }
    
    
}


Can anyone show me how should I accomplish this? Thank you very much!
Last edited on
I'd strongly advice against using cin >> for user input, though there's somewhat safe ways to do so.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
while (szInput != "NO MORE")
{
    cout << "Enter name: ";
    getline (cin, szInput, '\n');
    
    cout << "Enter score: ";
    cin >> iScore;

    cin.ignore (1000, '\n');
    cin.clear ();

    . . .

    for (unsigned int i = 0; i < szInput.length(); i++)
        szInput [i] = toupper (szInput [i]);
}
am i missing something?
 
if(name == v[i]) // when you declared string v[] ? 
Hi chipp! Sorry about the mistake. I changed the v into names. Thank you.

Hi Phil123, I am a beginner in C++ so I didn't learn about the getline() function yet. Do you see any other way I could do this on the basis of my code? Thank you!
Uhh, I suppose you could do it like this:
1
2
3
4
5
6
7
while (name != "NOMORE")
{
    cin >> name >> score;

    . . .

}


Or

1
2
3
4
5
6
7
8
9
while (true)
{
    cin >> name >> score;
    if (name == "NOMORE")
        break;

    . . .

}


Or

1
2
3
4
5
6
7
8
while (cin >> name >> score)
{
    if (name == "NOMORE")
        break;

    . . .

}


I personally think you should learn to use getline instead of working around the limitations of cin, but, your call.
Last edited on
Topic archived. No new replies allowed.