#include <iostream>
using namespace std;
void main(){
char name[20];
cin>>name; // when I input "This is"
cout<<name<<endl; // output was "This"
}
How to do that when I input "This is" , output too will be "This is" , not only "This" ?
You could use
cin.get( name, 20 );
or
cin.getline(name, 20);
Depending on whether you want the new line character in your string.
EDIT:
If you want to further simplify your code you could use a string instead of a char array, you wouldn't have to worry about the user exceeding your buffer size then ie.
string name;
getline(cin, name);
cout << name << endl;
EDIT 2:
As David Heffernan also pointed out in a comment I should explain why it's not working for you as expected. The extraction operator (operator >>) ends when a whitespace character -- a space in your case -- is reached. The operator also terminates when a null-character or the end of file is reached.
Related
the code that this problem acours on is this
#include <iostream>
int main() {
char name[20];
std::cout << "enter a name....";
std::cin >> name;
std::cout << "the name you entered was " << name;
system("pause");
}
it shows instead some weird stuff:
p 4464 70000 7000028207Press any key to continue . . .
I am using Dev-C++ IDE and its default compiler.
Why is that?
It would be good if you tell us the exact input of yours but the problem is probably that you do not account for the null terminator '\0'. When you use std::cin, it adds a null-terminator at the end of input stream. so if your input is 20 characters, you should actually use a char array of size 21. When you use 20, the program writes the null terminator past the end of array and it leads to an undefined behavior.
I'm making a c++ program using string(data type) and char array. Now, the data type is printing words alright. But, I'm having some trouble with the char array. Here's the code:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char str[200];
string str1;
cout<<"Enter a string:\t";
getline(cin,str1);
cout<<str1 <<endl;
cout<<"enter second string:\t";
cin>>str;
cin.get(str,200);
cout<<str;
}
code output
As, you can see in the output, the data type string is printing the words fine. But, the char array is missing the first word. Am I doing something wrong? or does the char array work in different way? Please explain. Thanks.
While you have already discovered that cin >> str; isn't required as you are simply writing again to str with cin.getline (str, sizeof str), there are a number of additional issues you should address:
1. Unless your compiler is ancient, you should #include <string>, not the C-header string.h;
2. Don't use magic-numbers in your code. If you need a constant, e.g. for the maximum number of characters in str, #define a constant or use a global enum to do the same, e.g.
#define MAXC 200 /* if you need a constant, #define one (or more) */
...
char str[MAXC]; /* don't use 'magic-number', use a constant */
That way when, and if you change the number of characters in str in the future, you don't have to pick through your entire code and change every occurrence of the magic-number, e.g. cin.get(str,200);.
3. Validate EVERY user input. Otherwise a failed input can set an error-bit on your input stream and additional attempts to read from a stream with an error-bit set can result in undefined behavior. You could do:
if (!getline(cin,str1)) { /* VALIDATE every input */
cerr << "error: input failure - str1.\n";
return 1;
}
and
if (cin.get (str, sizeof str))
cout << str << endl;
(note: there are no further attempted reads after cin.get (str, sizeof str) so guarding your use of str is sufficient)
4. Always output a newline after your final line output to ensure your program is POSIX compliant. Otherwise on many OS's you will mess up the users prompt if writing to stdout or you will create a non-POSIX compliant output file if redirecting the output to a file, e.g.
my cat has none01:22 wizard:~/dev/src-cpp/tmp/debug>
Putting it altogether, you could do something like:
#include <iostream>
#include <string> /* depending on your compiler */
#define MAXC 200 /* if you need a constant, #define one (or more) */
using namespace std;
int main (void) {
char str[MAXC]; /* don't use 'magic-number', use a constant */
string str1;
cout << "enter a string: ";
if (!getline(cin,str1)) { /* VALIDATE every input */
cerr << "error: input failure - str1.\n";
return 1;
}
cout << str1 << endl;
cout << "enter second string: ";
// cin >> str; /* not needed */
if (cin.get (str, sizeof str))
cout << str << endl;
}
Example Use/Output
$ ./bin/cin.get_getline
enter a string: my dog has fleas
my dog has fleas
enter second string: my cat has none
my cat has none
cout<<"enter second string:\t";
cin>>str;
cin.get(str,200);
here first you are trying to read the second word twice into same variable. comment one of them and try to print the content of str.
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char str[200];
string str1;
cout<<"Enter a string:\t";
getline(cin,str1);
cout<<str1 <<endl;
cout<<"enter second string:\t";
// cin>>str;
cin.get(str,200);
cout<<str<<endl;
}
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);
I want to write a constant string to a text file. I know it can be done by using put-to operator(<<), but I want to write that constant string in the block of data entered through cin, gets, etc. I need it for my school project. Please be nice and help me out. If the question isn't clear to you, let me know.
cout<<"Enter your name";
gets(name);
cout<<"Enter your roll number";
cin>>rollno;
char string[]="Student of XYZ School";
fout.write((char*)&student,size(student));
Note that char string can't be written with other data entered, but I want it to be written in the file with other data only.
If you have already done #include <iostream>, as you must have, why are you using gets() and write() and C-style strings? It would be much simpler, since this is C++, to use
#include <fstream>
string name;
string rollno;
ofstream outfile;
cout << "Enter your name";
cin >> name;
cout << "Enter your roll number";
cin >> rollno;
string str = "Student of XYZ School";
student.write(outfile);
You didn't say what type "student" is. In the example above, I assume that it is its own class. If it is, then you can define a member function for it
Student::write(ofstream &outfile) {
outfile << "blah blah blah";
// etc.
}
Whatever you do, DO NOT keep gets() in your program: it leaves your program open to a buffer overflow attack. If you can use cout, you can use cin.
I'm having an unpleasant problem with my c++ example. Everything works fine until I enter something with a whitespace.
#include <iostream>
using namespace std;
int main (int argc, char * const argv[])
{
int iteration = 0;
while (true) {
char * input = new char[256];
scanf("%s", input);
cout << ++iteration << ": " << input << endl;
cin.get();
}
return 0;
}
So with this code, I can enter anything, but everything after whitespace is somehow like stored in buffer and used in the second iteration.
foo
1: foo
bar
2: bar
foobar
3: foobar
foo bar
4: foo
5: bar
Every single input reading function acts like this and it's driving me crazy. cin >> input, freads(), cin.get() etc. all do this.
It this frequent problem with user input, or am I doing something wrong here?
First of all, never use scanf. It's difficult to use that function and avoid buffer overflows. Replace input with a std::string, and read from std::cin.
Both scanf("%s", input) and cin >> input will read one word, delimited by whitespace. If you want to read a whole line, then use getline(cin, input).
About scanf %s format specifier:
This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).
About istream::operator>> with str parameter:
Extraction ends when the next character is either a valid whitespace or a null character, or if the End-Of-File is reached.
So yes, this is standard behaviour for these functions.
Maybe try using std::getline instead?
http://www.cplusplus.com/reference/string/getline/