String Truncated for Some Reason in C++ [duplicate] - c++

This question already has answers here:
Issue with cin when spaces are inputted, using string class
(3 answers)
Closed 8 years ago.
So, I was just starting C++, and I have a problem. I declared a string variable and all that, but when I have input give the variable a value, then try to display it, it only shows the first word of the sentence.
#include <iostream>
#include <string>
using namespace std;
using std::string;
int main()
{
string answer;
cout << "Give me a sentence and I will repeat it!";
cin >> answer;
cout << answer;
return 0;
}
For example, I entered "Yay it worked!", and it outputted "Yay"

The delimiter for std::cin is whitespace, so it only took the first word of your sentence. Like #πάνταῥεῖ said, use std::getline(cin,answer) instead.

As the comment explains, cin will only read until the first bit of whitespace is met (in your case this seems to be a space). Instead, you can use std::getline, which will read until a specified character, or a return by default:
std::string answer;
std::cout << "Give me a sentence and I will repeat it!";
std::getline(std::cin, answer):
std::cout << answer;
To make it read until a specified character would look like:
char end_char = 'a';
std::getline(std::cin, answer, end_char);

Related

Function allows word but not Phrase c++ [duplicate]

This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 3 years ago.
I have a function that allows a user to input a word or phrase then display it on a menu but for some reason it will display a word but not a phrase, system crashes when I use more than one word
snippet of my function code:
string GetWord(void){
string localString = "";
cout<< "please enter a new word or phrase: ";
cin >> localString;
return localString;
}
does anyone know what I have done wrong ? the menu will display a single word but not double.
The input operator >> on std::cin stops reading at the first space and so just reads one word. This is the defined behavior.
I assume you would like to read until the user presses enter. You want to read a line. You can use std::getline() to achieve this:
std::string GetWordOrPhrase() {
std::string localString;
std::cout << "please enter a new word or phrase: ";
std::getline(std::cin, localString);
return localString;
}
BTW: Always use the std:: namespace explicitly in your code. Do not use using namespace std just to spare a few characters. (Code is not (only) about making it work with some compiler, but also a communication means between software developers.)

C++ : Getline Function Mechanics

#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
cin >> num;
string s;
getline(cin, s);
cout << s << " " << num << endl;
return 0;
}
In this code if I input 3 and press enter, then s takes an empty string.
1) If it is taking the first character as a newline, then is there a possible solution of taking line as input after taking an integer as input?
2) If my input is 4567artyu then how it is deciding whether 7 has to go into the s or num ?
I recommend that you always read complete lines of input from your users. It will cause the least confusion.
Ask for input.
Use std::getline to read a line of input.
If you don't want a string but, say, an integer, use std::stoi or (more general) boost::lexical_cast to safely convert the input to your desired target type. This is where you catch poor inputs and complain at the user.
I don't think that many users, if prompted for a number, would expect that entering 42bananas would be accepted as 42 and the bananas part be “remembered” for later. It will most likely be a typo and the user will be happy to be asked to correct it.
For taking line as input after taking integer as input you can consider removing the stray '\n' character from the stream.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
cin >> num;
getchar();
string s;
getline(cin, s);
cout << s << " " << num << endl;
return 0;
}
This will do the trick.
For second question, it reads 4567 as integer, it will continue to read it as integer until limit of int is reached and if limit is reached it will not consider anything after that. Then it will put the maximum value of int in the variable num and null int the string s. If limit is not reached, then string will remain in the input stream as it is, and will be fetched by variable s.
Try using cin.clear before you accept string

Why is my program getting a runtime error when I execute my code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This program is working without the loop, however when I implement the loop, I get a runtime error. I think it might have something to do with my cin.getline but I really have no idea :/ any help would be great thank you!
#include <iostream>
using namespace std;
#include <string>
#include <iomanip>
int main ()
{int ans, z;
z=1;
cout << "How many times would you like to execute this string program? " << endl;
cin >> ans;
while (z <= ans)
{
int x, i, y, v;
string answer1, str3;
string mystring, fname, lname;
i=0;
y=0;
cout << "Please enter your first and last name: ";
getline(cin, answer1);
cout << endl;
x=answer1.length();
for (int i = 0; i < x; i++)
{
cout << answer1[i] << endl;
if (isspace(answer1[i]))
{
y=i;
}
}
cout << endl << endl;
cout << setw(80) << answer1;
mystring = answer1;
v=answer1.find(" ", 0);
fname=mystring.substr(0, y);
lname=mystring.substr(v, x);
cout << "First name: " << fname << endl;
cout << "Last name: " << lname << endl;
mystring=lname+','+fname;
cout << setw(80) << mystring;
z++;
}
return 0;
}
The error happens in this line:
lname=mystring.substr(v, x);
where v happens to have a very large value. So how does your program get there, and how does v get this value? v has value std::string::npos, which is an error code meaning, in this case, that the space you were looking for wasn't there. That this is the case has to do with the difference between formatted and unformatted input and the fact that you're mixing them.
Formatted input means treating an input stream as a stream of tokens. Leading whitespace -- all whitespace, whether space, tab, or newline -- is skipped, and where the token ends, there does the input. One example of formatted input is
cin >> ans;
For formatted input, everything that doesn't fit its pattern looks the same. Whether std::istream::operator>>(int) encounters a space, a tab, a newline, an 'a' or a 'z', that's just the end of the token, and there it stops reading. For example, if you have
int x;
std::string s;
std::cin >> x >> s;
and feed it the input 123abc, then x will have the value 123, and s will be "abc". Crucially, this means that if the user answers
cin >> ans;
with a number and newline, the encountered character after the number -- a newline -- remains in the stream.
Unformatted input, by contrast, means treating an input stream as a stream of characters. For unformatted input functions, whitespaces are just another character, and unless the unformatted input function defines a special meaning for them, it will treat them the same as any other character. An example of unformatted input is
getline(cin, answer1);
which is shorthand for
getline(cin, answer1, '\n'); // that is to say, the delimiter
// has a default value of '\n'
(just to make it clear that the newline character '\n' has a special meaning in this case). getline, used this way, will read from the stream until it encounters a newline.
And therein lies your problem. After the previous, formatted input function, there is stuff left in the stream that you don't care about. It is probably just a newline (although if the user provided 123abc, it will be abc\n), in which case getline will give you an empty string -- there's an empty line in the stream, so what else can it do?
There are several ways to deal with this condition. One is to say
#include <iostream>
#include <limits>
cin.ignore(numeric_limits<streamsize>::max(), '\n');
This is essentially saying: ignore everything up to the next newline (the numeric_limits<streamsize>::max() is a very large number that cin.ignore treats as infinity). Another is
cin >> ws;
which says: "ignore everything up to the next non-whitespace character", although this will ignore leading spaces in the next line, and it will not ignore abc if the user provided 123abc. In your case, I believe there is no reason to change gears from formatted input -- you don't want a line but first and last names. I suggest using
string fname, lname;
cin >> fname >> lname;
This will also eliminate the other error (that you're using an error code as string index), because you won't have to search for a space in the string that may not be there.
Do
cin >> ans;
cin >> std::ws;
before the while loop. Also, check
v=answer1.find(" ", 0);
for
std::npos
which is the value returned if find was unsuccessful.

How to print out a certain part of a string [duplicate]

This question already has answers here:
How do I tokenize a string in C++?
(37 answers)
Closed 8 years ago.
EDIT:I see how it works now, in the string myString it takes everything after the space. So how would this be done if you wanted to take the first name and not the last name, since now you can't use the space if you do that.
I'd like to get the user to input their first and last name, then I'd like to print their last name only to the screen.
I know how to ask the user the question, and I was using getline to get the string of their name. But once that's happened how do I take their last name and print it out without printing out their first name as well. I can't seem to, I guess, isolate each part of the string.
I tried searching for an answer to this, but I can't seem to find one.
using namespace std;
int main()
{
string firstName;
string lastName;
cout << "Welcome to my store!" << endl;
cout << "---------------------------" << endl;
cout << "Please enter your first and last name. ";
getline(cin, firstName);
cout << "\nThank you " << firstName << " for shopping with us!";
}
I left the getline as is because I tried getline(cin, firstName, lastName) in an attempt to assign each word input by the user to a string but that didn't work.
I think this is what you are looking for(for printing the last name alone)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string myString;
int i;
cout<<"\n Enter a name:";
getline(cin, myString, '\n');//Get a name where first name and last name is seperated by a space
i=myString.find(' ');//find the find occurance of space in that string
cout<<"thanks for shopping:";
cout<<myString.substr(i,myString.length());//printing the rest of the string from the occurence of space
return 0;
}
When you give input like 'Sachin Tendulkar'
It says 'thanks for shopping:Tendulkar'

getline not asking for input? [duplicate]

This question already has answers here:
Need help with getline() [duplicate]
(7 answers)
Closed 7 years ago.
This is probably a very simple problem but forgive me as I am new.
Here is my code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string name;
int i;
string mystr;
float price = 0;
cout << "Hello World!" << endl;
cout << "What is your name? ";
cin >> name;
cout << "Hello " << name << endl;
cout << "How old are you? ";
cin >> i;
cout << "Wow " << i << endl;
cout << "How much is that jacket? ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << price << endl;
system("pause");
return 0;
}
The problem is that when asked how much is that jacket? getline does not ask the user for input and just inputs the initial value of "0". Why is this?
You have to be careful when mixing operator>> with getline. The problem is, when you use operator>>, the user enters their data, then presses the enter key, which puts a newline character into the input buffer. Since operator>> is whitespace delimited, the newline character is not put into the variable, and it stays in the input buffer. Then, when you call getline, a newline character is the only thing it's looking for. Since that's the first thing in the buffer, it finds what it's looking for right away, and never needs to prompt the user.
Fix:
If you're going to call getline after you use operator>>, call ignore in between, or do something else to get rid of that newline character, perhaps a dummy call to getline.
Another option, and this is along the lines of what Martin was talking about, is to not use operator>> at all, and only use getline, then convert your strings to whatever datatype you need. This has a side effect of making your code more safe and robust. I would first write a function like this:
int getInt(std::istream & is)
{
std::string input;
std::getline(is,input);
// C++11 version
return stoi(input); // throws on failure
// C++98 version
/*
std::istringstream iss(input);
int i;
if (!(iss >> i)) {
// handle error somehow
}
return i;
*/
}
You can create a similar function for floats, doubles and other things. Then when you need in int, instead of this:
cin >> i;
You do this:
i = getInt(cin);
Its because you have a '\n' left lying on the input stream from a previous call.
cin >> i; // This reads the number but the '\n' you hit after the number
// is still on the input.
The easiest way to do interactive user input is to make sure each line is processed independently (as the user will hit enter after each prompt).
As a result always read a line, then process the line (until you get familiar with the streams).
std::string line;
std::getline(std::cin, line);
std::stringstream linestream(line);
// Now processes linestream.
std::string garbage;
lienstream >> i >> garbage; // You may want to check for garbage after the number.
if (!garbage.empty())
{
std::cout << "Error\n";
}
Ignore some characters until line feed is reached.
cin.ignore(256, '\n')
getline (cin,mystr);