This question already has answers here:
getline not asking for input? [duplicate]
(3 answers)
Closed 2 years ago.
int main() {
string s1,s2;
cout<<"1. "<<endl;
cin>>s1; //to accept 1st string
cout<<s1<<endl;
cout<<"2. "<<endl;
getline(cin,s2); //to accept 2nd string
cout<<s2<<endl;
}
Here in the above code after accepting the 1st string it is not asking for the 2nd string: the program is getting terminated after taking the 1st input without waiting for the 2nd.
Could anyone kindly explain what the reason of such behavior is? And why is it not waiting for getline(cin,s2) for taking user input?
That is happening because getline reads \n at the end of your first line. So it read and printed "\n" while you think it expects a new line.
I suggest use getline twice (so firstly it reads \n, then your second line). And please, use std::, don't use using namespace std, and use spaces as any normal codestyling sais.
int main() {
std::string s1, s2;
std::cout << "1. " << std::endl;
std::cin >> s1; //to accept 1st string
std::cout << s1 << std::endl;
std::cout << "2. " << std::endl;
std::getline(std::cin, s2); //to accept \n
std::getline(std::cin, s2); //to accept 2nd string
std::cout << s2 << std::endl;
}
Here the error is there you need misunderstand the return type . Here you have used int for main method . So there you need return type. If you have used void for main method you haven't need a return type . You can use modify the code as below .
This is for printing single string
#include <iostream>
using namespace std;
int main(){
string s1;
cout<<" Enter the first string :"
getline(cin,s1);
cout<<"The input string is"<<s1 <<endl;
return 0;
}
You can modify the code as below to output the two strings as below
#include <iostream>
using namespace std;
int main(){
string s1,s2;
cout<<" Enter the First string :"
getline(cin,s1);
cout<<"The First string is"<<s1 <<endl;
cout<<" Enter the Second string :"
getline(cin,s2);
cout<<"The Second string is"<<s2 <<endl;
return 0;
}
Related
When I am trying to store more than one word in a string variable, it only outputs one word when I tell the program to print it. This is an example:
#include <iostream>
using namespace std;
string i;
int main() {
cout << "Input more than one word." << endl;
//in this case the user will input whats up//
cin >> i;
cout << i << endl;
//the program outputs 'whats'//
}
Instead of using cin >> i, use getline(cin, i).
The difference is that, with getline() you get all the words in a line, whereas with operator>> you get only one word at a time.
Replace that:
cin >> i;
for:
getline(cin, i);
and it will work :)
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 4 years ago.
I'd like to do the following, but without including string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1,s2;
char c;
cout<<"input a string: "<<endl;
cin>>s1;
cout<<"input a character: "<<endl;
cin>>c;
cout<<"input another string: "<<endl;
cin>>s2;
}
When I try this:
#include <iostream>
using namespace std;
int main()
{
char s1[128], s2[128];
char c;
cout << "input a string: " << endl;
cin.getline(s1, 128);
cout << "input a character: " << endl;
cin >> c;
cout << "input another string: " << endl;
cin.getline(s2, 128);
}
I run into issues... basically when I enter the character it also enters for the second string, and I never get a chance to enter it. please help thanks.
Rik
Use cin.get() after use "cin >> var". This method extract symbol new line from buffe
This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 4 years ago.
int main(){
char str1[MAX], str2[MAX];
cout <<" 1st string: ";
cin.get(str1, MAX);
cout <<" 2nd string";
cin.get(str2, MAX);
cout << str1 << str2;
return 0;
}
I am trying to input a string with spaces included in both arrays str1 and str2. The problem is program terminates after taking the first input.
On the output screen:
1st string : abc def
Now when I press enter to take input for 2nd array but then the code terminates and first string is displayed.
Output:
2nd string
abc def
How can I properly use this cin.get() function to take 2 different inputs? Is there any other way to take string with blank spaces for char array ?
std::string _str;
std::getline (std::cin, _str);
// std::getline (std::cin, _str, _char);
// if you wish to accept input until first appearance of _char
function getline() handles input that contains
embedded blanks or multiple lines.
#include <iostream>
#include <string> //for string class
using namespace std;
int main()
{ //objects of string class
string full_name, address;
getline(cin, full_name); //reads embedded blanks
cout << “Your full name is: “ << full_name << endl;
getline(cin, address, ‘$’); //reads multiple lines
cout << “Your address is: “ << address << endl;
return 0;
}
first argument is the stream object from which the input will
come.
second argument is the string object where the text will be placed.
The third argument specifies the character to be used to terminate the input.
If no third argument is suppliedto getline(), the delimiter is assumed to be ‘\n’, which represents the Enter key.
Instead of cin.get() method use the following approach:
string s1,s2;
int max1,max2;
for (int i=0; i<max1; i++)
{
char ch = getchar();
while (ch != '\n' && ch != EOF) {
s1+=ch;
ch=getchar();
}
for (int i=0; i<max2; i++)
{
char ch = getchar();
while (ch != '\n' && ch != EOF) {
s2+=ch;
ch=getchar();
}
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 7 years ago.
I have a little problem. I've created a program that asks user to enter part's name and part's price for four diffrent parts. Each name and price fills a structure, and I have an array of four structures. When i do a for loop to fill all the names and prices, my getline functon doesn't work properly, it simply just skipps the entering part after I enter the first part's name. Can you please tell me why?
Here's my code:
#include <iostream>
#include <string>
struct part {
std::string name;
double cost;
};
int main() {
const int size = 4;
part apart[size];
for (int i = 0; i < size; i++) {
std::cout << "Enter the name of part № " << i + 1 << ": ";
getline(std::cin,apart[i].name);
std::cout << "Enter the price of '" << apart[i].name << "': ";
std::cin >> apart[i].cost;
}
}
std::getline consumes the newline character \n, whereas std::cin will consume the number you enter and stop.
To illustrate why this is a problem, consider the following input for the first two 'parts':
item 1\n
53.25\n
item 2\n
64.23\n
First, you call std::getline, which consumes the text: item 1\n. Then you call std::cin >> ..., which recognises the 53.25, parses it, consumes it, and stops. You then have:
\n
item 2\n
64.23\n
You then call std::getline for a second time. All it sees is a \n, which is recognised as the end of a line. Therefore, it sees a blank string, stores nothing in your std::string, consumes the \n, and stops.
To solve this, you need to make sure the newline is consumed when you store the floating-point value using std::cin >>.
Try this:
#include <iostream>
#include <string>
// required for std::numeric_limits
#include <limits>
struct part {
std::string name;
double cost;
};
int main() {
const int size = 4;
part apart[size];
for (int i = 0; i < size; i++) {
std::cout << "Enter the name of part № " << i + 1 << ": ";
getline(std::cin,apart[i].name);
std::cout << "Enter the price of '" << apart[i].name << "': ";
std::cin >> apart[i].cost;
// flushes all newline characters
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
This question already has answers here:
How to check std::string if its indeed an integer?
(3 answers)
How to say != 0-9 in c ++ [duplicate]
(6 answers)
Closed 9 years ago.
I have got a terminal app that gets user input stores it in a string then converts it into a int. The problem is if the user inputs anything that is not a number the conversion fails and the script continues without any indication that the string has not converted. Is there a way to check of the string contains any non digit characters.
Here is the code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string mystr;
float price=0;
int quantity=0;
cout << "Enter price: ";
getline (cin,mystr); //gets user input
stringstream(mystr) >> price; //converts string: mystr to float: price
cout << "Enter quantity: ";
getline (cin,mystr); //gets user input
stringstream(mystr) >> quantity; //converts string: mystr to int: quantity
cout << "Total price: " << price*quantity << endl;
return 0;
}
Just before the conversion here: stringstream(mystr) >> price; I want it to print a line to the console if the string is Not a Number.
You can find out if a read of an int has been successful or not by checking the fail() bit of your input stream:
getline (cin,mystr); //gets user input
stringstream priceStream(mystr);
priceStream >> price;
if (priceStream.fail()) {
cerr << "The price you have entered is not a valid number." << endl;
}
Demo on ideone.
If your want to check if the price user inputs is a float, you can use boost::lexical_cast<double>(mystr);, if it throws an exception then your string is not a float.
It's going to add a bit to your code, but you can parse mystr with isdigit from cctype. The library's functions are here. isdigit(mystr[index]) will return a false if that character in the string isn't a number.