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 :)
Related
I'm new to C++ programming, and I've come upon a roadblock. Here's my code:
#include <iostream>
using namespace std;
int main(){
int sum = 0, a;
cout << "enter first set of numbers:";
while(cin >> a) sum += a;
cout << "first sum = " << sum;
cin.clear();
cin.ignore( numeric_limits<streamsize>::max(), '\n');
sum = 0;
cout << "enter second set of numbers:";
while(cin >> a) sum += a;
cout << "second sum = " << sum;
}
I'm trying to sum two sets of numbers that I input at the command line. The problem is that when I hit ctrl-d to terminate my first set of numbers, it skips the second set of cin's. Most of the pages I find elsewhere on the internet tell me to use cin.clear and cin.ignore. I've tried that and it still doesn't work. This page question concerning cin.clear() even seems to have the same problems. However, the fixes they suggest don't work for me.
Does this code above work for anyone else?
When you use Ctrl-D you terminate the input stream: there is no further character coming from std::cin. Even clearing the stream doesn't help: you have told the stream it is at its end. You can't reopen it. However, clear()ing the stream and using ignore() is the solution to your problem!
You need a different indicator that one set of values is done. The easiest is to use a non-digit character or string: trying to read something which isn't an int will cause the stream to go into failure mode [without closing the stream]. That is, you read until the conversion fails, clear() the stream, and ignore() everything up to the end of the line.
Your code should already do that: instead of using Ctrl-D just enter, e.g., x.
//Use stringstream ^^ for multiple user input
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main (void)
{
string mystr;
float price = 0;
int quantity = 0;
cout << "Enter price: ";
getline (cin, mystr);
stringstream(mystr) >> price;
cout << "Enter quantity:";
getline (cin, mystr);
stringstream(mystr) >> quantity;
cout << "Total price: " << price*quantity << endl;
return 0;
}
You can use Ctrl-D, you just need to have your loop in another thread. So Ctrl-D, kills the thread, then returns to your main function, then you can start another thread.
It'd not the best solution, but it can work, http://codebase.eu/tutorial/posix-threads-c/
I ran into an interesting problem when playing around with input streams in C++.
I know that if you attempt to enter a string that contains spaces using cin it will truncate the string at the first space unless you use getline to get the string.
However I found that even more unexpected results can occur ... If you have a second cin after the first one, and the first cin has spaces in it's input, the second input is skipped and its value is clobbered!
Why does this happen?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string myString;
int myInt;
// I know this will cut off the end of the string
cout << "Enter a string with spaces: ";
cin >> myString;
cout << endl;
cout << "Enter an integer: ";
cin >> myInt;
cout << endl;
cout << "String: " << myString << endl;
cout << "Int : " << myInt << endl;
return 0;
}
Output:
Enter a string with spaces: This is a string
Enter an integer:
String: This
Int : -858993460
Is there a way to trap on this error so an ignorant user doesn't enter a string with spaces and break an entire program?
Reading from cin does not read a whole line and then only return part of it. Conceptually, it reads a 'token', usually understood to mean a whitespace-separated string, and then parses it into whatever type you are reading. It has no concept of a 'line'. All the input lines are one consecutive stream of tokens. So after reading a string ("This"), the next token is "is", which of course cannot be parsed as an int, and thus the error.
I saw a similar question to mine: C++ string variables with if statements
The only difference between his situation and mine is that I would like the condition to be if a string with a space is matching a certain string.
Here is my code:
#include <iostream>
#include <string>
int main()
{
using namespace std;
string input1;
cout << "Welcome to AgentOS V230.20043." << endl;
cout << "To log in, please type \"log in\"" << endl;
cin >> input1;
if (input1 == "log in")
{
cout << "Please enter your Agent ID." << endl;
}
return 0;
}
For some reason, the if statement is not picking up the string. However, if the conditions is:
if (input1 == "login"
It works. I cannot find a way to use a string with a space in it with a condition. I am wondering if maybe the if statement is okay but that the cin is deleting the space.
Thank you!
You should use standard function std::getline instead of the operator >>
For example
if ( std::getline( std::cin, input1 ) && input1 == "log in" )
{
std::cout << "Please enter your Agent ID." << std::endl;
}
cin >> ignores whitespace, use getline:
getline(cin, input1);
You need to read the entire line with spaces with std::getline, it will stop when finds a newline \n or N-1 characters. So, just do the reading like this:
cin.getline( input1, N );
Where N is the max number of character that will read.
Here's my actual code, it's skipping the getline(cin,phrase) completely..
maybe there's something else wrong with it, but I can't really find anything wrong.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ofstream outFile;
string file_name;
string phrase;
int number;
cout << "What file would you like to write into? ";
cin >> file_name;
outFile.open(file_name);
if(!outFile)
{
cout << "Error, could not find file. Press enter to self destruct. " << endl;
return -1;
}
cout << "What would you like to write? ";
getline (cin, phrase);
cout << "How many times? ";
cin >> number;
while(number != 0)
{
outFile << phrase;
number = number - 1;
}
system("pause");
return 0;
}
cin would read as far as whitespace is not there in your input string. To get around that you can use
getline( cin, cookie ).
OR
char input[100];
cin.getline(input,100);
EDITED AS TO CLARIFY:-
Show me the output for this :-
#include <iostream>
#include <string>
using namespace std;
int main()
{
string cookie;
getline ( cin, cookie );
cout << cookie;
system("pause");
return 0;
}
The >> operators read formatted input in term of "space separated items", so
aaaaa bbbb 123
are actually three distinct elements. The first two can be string, the third can be a string or whatever numeric scalar type.
If you want to consider spaces as part of the read, the proper function shold be getline
Here is my code for a basic copycat program that just copys whatever the user types:
#include <iostream>
using namespace std;
#include <string>
int main()
{
cout << "type something.. I dare you..." << endl;
for (;;)
{
string usrin;
cout << "You: ";
cin >> usrin;
cout << "Me: " << usrin;
}
return 0;
}
But when the user inputs more than one word i get this:
Me: more
You: than
You: Me: one
You: Me: word
You:
any and all help is appreciated! thank you!
You need to use cin.getline(usrin) instead of cin >> usrin.
cin >> usrin stops reading when it finds whitespace characters in the stream but leaves the rest of the stream for the next time cin is used.
cin.getline will read until the end of the line. However, you will need to change usrin to an array of char.
char usrln[MAX_LINE_LENGTH];
where MAX_LINE_LENGTH is a constant that is bigger than the length of the longest line you expect to see.
After each input, \n leaved behind in input buffer and read on next iteration. You need to flush your input buffer. Use
cin.ignore(MAX_INT, '\n'); //Ignores to the end of line
Add <limits.h> header.
#include <iostream>
#include <limits.h>
#include <string>
using namespace std;
int main()
{
cout << "type something.. I dare you..." << endl;
for (;;)
{
string usrin;
cout << "You: ";
cin >> usrin;
cout << "Me: " << usrin ;//<<endl;
cin.ignore(INT_MAX, '\n');
}
return 0;
}