I have following Simple program to print string in C++, But this program only reads characters before space, not reading full string.
#include<iostream>
using namespace std;
int main()
{
char str[90];
cout << "Enter a string:";
cin >> str;
cout << str;
system("pause");
}
This is by design: cin "breaks" lines on whitespace characters, such as spaces and tabs.
Moreover, you are limiting the input to 90 characters, which is not good either: typing more than 90 characters with no spaces in between would overflow the buffer.
Here is a way to fix it:
std::string str;
std::cout << "Enter a string: ";
std::getline(std::cin, str);
Unlike character arrays, std::string objects can grow dynamically, so they would accommodate any number of characters the user chooses to enter.
You need to add two headers in order for this to compile:
#include <string>
#include <iostream>
>> reads a single word. You want getline to read a whole line:
cin.getline(str, sizeof str);
Now the problem is that the line will be truncated if it's too long. To fix that, use a string rather than a fixed-size buffer:
string str;
getline(cin, str);
Related
about the code below, string doesn't light up anymore and when I entered "John Smith", only "John" appears, string was working fine for me weeks ago until i tried calling strings function today which didn't work so i tested for a simpler one.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string name;
// Get the user's name
cout << "Please enter your first name: ";
cin >> name;
// Print the greeting
cout << "Hello, " << name << "." << endl;
return 0;
}
string doesn't light up like int
I might be asking at the wrong place but I cant' tell what's the problem, please help :(
To get all the line, use getline(cin, name);
instead of cin >> name;
See http://www.cplusplus.com/reference/string/string/getline/
With std::string's, using std::cin >> someString will only read the first word off the buffer (it will stop at the first whitespace encountered).
Use getline(std::cin, someString) instead to read the entire line.
std::cin gets only characters to first 'white' character, like space, tab or enter.
If you want to read whole line use e.g. getline()
string line;
cin.clear(); //to make sure we have no pending characters in input buffer
getline(cin, line);
I was writing this code below that is suppose to take in information from the user ( a sentence ) and remove the desired letter. However, it only works if that sentence is one word. If the information contains a space, it will terminate at the space.Any advice as how I can get the program to read the entire sentence?
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string sentence;
char letterRemoved;
//Entering in Information
cout <<"Enter a sentence here!";
cin >> sentence;
cout <<"Enter letter to remove";
cin>>letterRemoved;
//Removing Occurence of letter
sentence.erase(remove(sentence.begin(), sentence.end(),letterRemoved), sentence.end());
//Print out
cout<<sentence << "\n";
return 0;
}
Reading input using cin >> sentence only reads until whitespace is encountered, and then stops. If you want to read an entire line (until the user presses enter), you want to use std::getline:
getline(cin, sentence);
Alternately, if you want to read up until a full stop character or a newline is found, you can use the delimeter argument to getline:
getline(cin, sentence, '.');
I'm supposed to force the user to input a number then a space then a string and if the format was wrong, I should terminate the program. When I used the cin, the compiler ignored the space and considered the first character of the string to be the one he should check to make sure that the user inputs a space and since the first character is always not a space he terminates.
What should I do ?!
I assume by "when I used the cin" you mean with the >> operator. Reading from an istream with >> is a formatted input function which means the input is pre-formatted for you, one of the effects is skipping over whitespace by default.
There are several ways to solve your problem, including reading a single character at a time (using an unformatted input function such as std::istream::get) or reading a line at a time and parsing the line.
Alternatively, you can turn off skipping of whitespace characters with the noskipws manipulator:
#include <iostream>
#include <string>
int main()
{
int num;
char c;
std::string str;
if (std::cin >> std::noskipws >> num >> c >> str && c == ' ')
std::cout << "ok" << std::endl;
else
std::cout << "Failed" << std::endl;
}
Use std::getline. If you require further help, make sure to post a code sample which demonstrates the problem, otherwise you won't get specific answers.
Example:
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cout << "Please enter a number and a string, separated by a space:";
std::getline(std::cin, input);
// Code to validate input
}
My code has to identify whitespace characters using cin, so when I use space as an input it should identify the space. How do I do this?
You can use std::noskipws to disable the whitespace skipping that std::cin does by default:
#include <iostream>
#include <iomanip>
int main() {
char c;
std::cin >> std::noskipws;
while (std::cin >> c) {
if (c == ' ')
std::cout << "A space!" << std::endl;
}
return 0;
}
string str;
getline(cin, str); // get the whole line
If you want to deal with c-strings you could use the mentioned cin.getline(....) which is different from strings getline.
Cin breaks on whitespace, of any kind. If you need to read an entire line, you need to use the get line function:
getline(cin, line);
Where line is a std::string. This will still cut off any new lines or carriage returns.
To test the string for spaces examine every character in the string and compare it to the space character " ". That is left as an exercise for the reader ;)
Use cin.getline to read the line with the space.
http://www.cplusplus.com/reference/iostream/istream/getline/
i have a little problem on writing the string into a file,
How can i write the string into the file and able to view it as ascii text?
because i am able to do that when i set the default value for str but not when i enter a str data
Thanks.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
fstream out("G://Test.txt");
if(!out) {
cout << "Cannot open output file.\n";
return 1;
}
char str[200];
cout << "Enter Customers data seperate by tab\n";
cin >> str;
cin.ignore();
out.write(str, strlen(str));
out.seekp(0 ,ios::end);
out.close();
return 0;
}
Please use std::string:
#include <string>
std::string str;
std::getline(cin, str);
cout << str;
I'm not sure what the exact problem in your case was, but >> only reads up to the first separator (which is whitespace); getline will read the entire line.
Just note that >> operator will read 1 word.
std::string word;
std::cin >> word; // reads one space seporated word.
// Ignores any initial space. Then read
// into 'word' all character upto (but not including)
// the first space character (the space is gone.
// Note. Space => White Space (' ', '\t', '\v' etc...)
You're working at the wrong level of abstraction. Also, there is no need to seekp to the end of the file before closing the file.
You want to read a string and write a string. As Pavel Minaev has said, this is directly supported via std::string and std::fstream:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ofstream out("G:\\Test.txt");
if(!out) {
std::cout << "Cannot open output file.\n";
return 1;
}
std::cout << "Enter Customer's data seperated by tab\n";
std::string buffer;
std::getline(std::cin, buffer);
out << buffer;
return 0;
}
If you want to write C, use C. Otherwise, take advantage of the language you're using.
I can't believe no one found the problem. The problem was that you were using strlen on a string that wasn't terminated with a null character. strlen will keep iterating until it finds a zero-byte, and an incorrect string length might be returned (or the program might crash - it's Undefined Behavior, who knows?).
The answer is to zero-initialize your string:
char str[200] = {0};
Supplying your own string as the value of str works because those in-memory strings are null-terminated.