Reputation: 5460
Here's my C++ code right now:
// Prompt user loop
char preInput;
do {
// Fill the vector with inputs
vector<int> userInputs;
cout << "Input a set of digits: " << endl;
while(cin>>preInput){
if(preInput == 'Q' || preInput == 'q') break;
int input = (int) preInput - '0';
userInputs.push_back(input);
}
// array of sums sync'd with line #
int sums[10] = {0};
// Calculate sums of occurance
for(vector<int>::iterator i = userInputs.begin(); i != userInputs.end(); i++){
int currInput = *i;
for(int numLine = 0; numLine < lines.size(); numLine++){
sums[numLine] += lineOccurances[numLine][currInput];
}
}
int lineWithMax = 0;
for(int i = 0; i < 10; i ++)
if(sums[i] > sums[lineWithMax]) lineWithMax = i;
cout << lines[lineWithMax] << endl;
// Clear vector
userInputs.clear();
} while (preInput != 'Q' && preInput != 'q')
Don't worry about the function of the loop, I just need it to run in a certain way. If a user types in "123" the loop should load the chars 1,2,3 into userInputs as separate elements. Upon hitting enter, the loop needs to execute all of the code below the while(cin>>preInput){} statement, clear the userInput vector, and repeat until the character Q is entered. This is not what's happening. The way the loop is currently written, The program takes user input until the user hits Q, enter essentially does nothing. I need the code to execute whenever the user hits enter. I've been playing with this for a while but I'm not too familiar with taking data through a char into a vector via cin so I'm not sure how to do this...Can anyone point me in the right direction?
Would changing the cin>>preInput to a getline work? Or would this attempt to put the value say..."123" into the char preInput as one assignment? I need the vector to receive the numbers separately rather than all together as one element. To reiterate, if the user enters "123" userInputs[0] should be 1, userInputs[1] should be 2...and so on.
Essentially, the only thing that needs to be changed is that the while(cin>>preInput){} loop must break when the user hits enter.
Upvotes: 0
Views: 2748
Reputation: 103693
Read a line with getline
, then split that line up using istringstream
.
std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
while(iss>>preInput){
if(preInput == 'Q' || preInput == 'q') break;
int input = (int) preInput - '0';
userInputs.push_back(input);
}
Or, since you're just looking at one character at a time, you can just look directly at the characters of the string.
for (char c : line)
{
if (c == 'Q' || c == 'q') break;
int input = c - '0';
userInputs.push_back(input);
}
Upvotes: 1