Trying to split a string into two integers [duplicate] - c++

This question already has answers here:
How to read n integers from standard input in C++?
(7 answers)
Closed 7 years ago.
So I want to split a string (entered to the console) into two integers.
The first integer will always be one digit at position 0 in the string. Then, there will be a space. Everything after that space will be the second digit.
Here is my code:
struct priority_element
{
int id;
int priority;
} priorityQueue[1000];
string input;
cin << input;
priority_element temp;
string priority = input.substr(0, 1);
string id = input.substr(1, input.size());
temp.priority = atoi(priority.c_str());
temp.id = atoi(id.c_str());
priorityQueue[0] = temp;
cout << priorityQueue[0].priority;
cout << priorityQueue[0].id;
I included the priority_element struct so you could see what it was.
I keep trying to enter a string, something like:
5 6
or
5 5000
I can print the priority (5), but printing the priority and id together like in my example code has the output of 50.
If I try to print the id alone then the output is empty.
Could anyone understand why this is happening?
Thanks!

std::cin will stop passing at spaces, so you should read the whole line to input by using
// cin >> input;
std::getline(cin, input);
As suggested by others, actually, this can be done simply by:
std::cin >> temp.priority >> temp.id;

The streams in C++ are made for just this type of thing.
(from iostream)
int x,y;
std::cin >> x;
std::cin >> y;
std::cout << x << y << std::endl;

string id = input.substr(1, input.size());
here you got a space not the second digit
English is not my first langage , hope you can understand

Related

While loop repeats for every word in a string in C++

I am trying to make a magic 8 ball that provides a random preset answer to any input except "bye". Each time the void function magic8ball() is called, it generates a random number from 0 - 19 and prints a corresponding response to the console.
int main()
{
string question;
cin >> question;
while (question != "bye") {
magic8ball();
cout << "~Ask another question.\n";
cin >> question;
}
return 0;
}
For some reason, if the input for question has more than one word / has whitespace between characters, the loop repeats for each word before asking for input again. I stuck a "cout << question << endl;" in there and it showed each word in the string (as well as a call of magic8ball and "ask another").
e.g
>hi frend
... Ask again later
hi
~Ask another question.
... Don't count on it
frend
~Ask another question.
How do I prevent the while loop from treating the string as a series of words? Why is cin not triggering along with magic8ball() and cout ?
std::cin stops reading when it sees whitespace. Space also counts as a whitespace.
If you want your string to have space, use std::getline()
int main()
{
string question;
std::getline(std::cin, question);
while (question != "bye") {
magic8ball();
cout << "~Ask another question.\n";
std::getline(std::cin, question);
}
return 0;
}

Why does my loop run multiple times continuously without prompting me for input? [duplicate]

This question already has answers here:
Code for getting multiple words in a string from user
(5 answers)
Closed 1 year ago.
while (inputstr != "The End") {
// Read in a String from the user
std::cout << "Please enter a string:\n";
std::cin >> inputstr;
}
This is the code I have written, in C++. For some reason, whenever I enter a string, if the string has multiple words to it, like "hello hello", then "Please enter a string:" gets printed 2 times consecutively, instead of only once. If I enter a one word string, it only prints once. If I enter a 3 word string, it prints that line 3 times, and so on.
In your code , std::cin >> inputstr;cin will read only one word (means a string before space). After space cin will consider the input as next string.
Solution for this is to use getline() function at the place of cin like :
while (inputstr != "The End") {
// Read in a String from the user
std::cout << "Please enter a string:\n";
// std::cin >> inputstr;
getline (cin , inputstr);
}

the string input got ignored after the first input

I tried to input string inside the function, getline(cin, worker->Name) works for the first time input but for the next input it skips or got ignored. it works for the integer but it doesn't work for the string, what should I do?
Code:
#include <iostream>
using namespace std;
struct Worker {
string Name;
int Salary;
int Status;
int Child;
};
void InputWorkerData(Worker *worker) {
cout << "Nama: ";
getline(cin, Worker->Name);
cout << "Gaji per bulan: ";
cin >> worker->Salary;
cout << "status (menikah = 1, single = 0): ";
cin >> worker->Status;
if(worker->Status == 1) {
cout << "jumlah anak: ";
cin >> worker->Child;
} else {
worker->Child = 0;
}
cout << endl;
}
int main() {
Worker worker1, worker2, worker3;
InputWorkerData(&worker1);
InputWorkerData(&worker2);
InputWorkerData(&worker3);
return 0;
}
Output:
Nama: michael jordan
Gaji per bulan: 7000
status (menikah = 1, single = 0): 1
jumlah anak: 3
Nama: Gaji per bulan: 5000
status (menikah = 1, single = 0): 0
Nama: Gaji per bulan: 9000
status (menikah = 1, single = 0): 1
jumlah anak: 2
Mixing line-oriented and item-oriented input can (and often will) lead to problems like this.
This seems to fit the typical case: after reading an item (in this case a number) using >>, there's a new-line character still sitting in the input buffer. When you call getline, it sees that new-line character as the end of an otherwise empty line.
There are a few ways to avoid this problem. One common, well-known one is to use getline to read input a line at a time throughout, then use (for one possibility) a lexical_cast to convert the data from a string to the type you actually wanted to read.
use fflush(stdin) after each input i.e after cout and before getline() .It will solve your problem.you have to flushout the buffer first.

Why do fflush(stdin) have no effect on the output? [duplicate]

This question already has answers here:
Using fflush(stdin)
(7 answers)
Closed 3 years ago.
I wrote this simple addition software, in which I wanted the addition to end when the user entered 'n'. My current code works just fine. But I made two more variations of the same code, one worked, and one gave me an error. Can anyone tell me what is happening exactly in each case?
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
cin>>a;
b+=a;
}while(getchar()!='n');
cout<<b;
//works just fine
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
fflush(stdin);
cin>>a;
b+=a;
}while(getchar()!='n');
cout<<b;
//this one works too
int a, b=0;
cout<<"Welcome to my Addition Software!!\n\n";
do{
a=getchar();
b+=a;
}while(a!='n');
cout<<b;
//doesn't work
I wanna know why fflush(stdin) have no effect on the code. If I just keep writing my input like "20, 30, 50, n" instead of "20, y, 30, y, 50, n" I get the same result in both working codes. Why does this happen?
First of all, it is best to use C++ standard input and output std::cin and std::cout respectively.
The main problem with your code is that it conflicts with types you want:
You want to add integers int together and to see if the input is the character char 'n'.
What's happening is the legacy C fflush(stdin) "flushes" or clears the standard input stream buffer (read more here: https://www.google.com/amp/s/www.geeksforgeeks.org/use-fflushstdin-c/amp/) and getchar() receives character input from the user. getchar() returns a character and by deduction, your code transmutes that input into its integral int ASCII-ANSI numerical integral equivalent.
This means that on the third version, when you input "30", what actually is collected is '3' and without flushing the buffer, the next input is considered '0' causing a problem.
I suggest you use a control structure to check if the user wants to continue before receiving input to add:
int a = 0, b =0;
char c = 0; // for y/n responses
std::cout << "Welcome to my ... "; //just finish this string
do{
std::cout << "input integer: "; // for better formatting leave at least one space after the colon
std::cin >> a;
b += a;
std::cout << "Continue? n to stop: "
std::cin >> c;
} while (c != 'n')
std::cout << "Added: " << b;

getline does not take any input [duplicate]

This question already has answers here:
Need help with getline() [duplicate]
(7 answers)
Closed 7 years ago.
I need to use getline to store whole line when user enters name and surname. When I run the program, it passes row of getline(cin,st[i].name); I mean the input function does not work, it skips next cin which is for "score".
struct Student {
string name;
int score;
char grade;
};
void main() {
int SIZE;
cout << " How many students are you going to add ? ";
cin >> SIZE;
Student* st = new Student[SIZE]; // user determines size of array.
int i;
for (i = 0; i < SIZE; i++)
{
if (st[i].name.empty()) // if array list of name is empty, take input.
{
cout << "name and surname : ";
//cin >> st[i].name;
getline(cin, st[i].name);
}
cout << "Score : ";
cin >> st[i].score; // take quiz score from user.
-- I did not put whole main function.
So when l run the program, back screen is shown
Is there any other way to get input for name ?
After cin >> SIZE;, the trailing newline is still kept in standard input.
You need cin.ignore() to skip the remaining newline character so the later getline() could get the value.