char ch[4];
char* ptr;
ptr = ch;
while(1)
{
cin >> *ptr;
if(*ptr == '\n')
break;
ptr++;
}
Here I just wrote a bit of sample code where I am trying to get out of a while loop when user writes ENTER but it's not working. Please help me. Thank you in advance.
To get a single character, use std::istream::get. This should work for getting newlines as well.
But instead of getting characters in a loop until you get a newline, why not just use something like std::getline:
std::string str;
std::getline(cin, str);
Or if you only want to get max three characters you can use std::istream::getline:
char ch[4];
cin.getline(ch, 4, '\n');
You are reading input into the value of a character. That's what *ptr means. I think you want just plain ptr, which is a pointer to an array of characters, which is something that is meant to receive data. What you wrote is basically this:
char c;
cin >> c;
I don't think that's what you meant, nor would it work even if it were, since as Joachim Pileborg points out above, the >> operator skips whitespace like newlines. In general, it is always best to be very robust when it comes to reading input. Provide adequate space, and either use a variable that can grow automatically (like std::string) or tell the system how much space you have (like fgets()).
The following will read a line:
istream& getline (char* s, streamsize n );
The extraction operator would skip leading white-spaces and stop execution on encountering any subsequent white-space. So, when you want to do something like this, use std::istream::get() or std::istream::getline().
Related
When should std::cin.getline() be used? What does it differ from std::cin?
Let's take std::cin.getline() apart. First, there's std::. This is the namespace in which the standard library lives. It has hundreds of types, functions and objects.
std::cin is such an object. It's the standard character input object, defined in <iostream>. It has some methods of its own, but you can also use it with many free functions. Most of these methods and functions are ways to get one or more characters from the standard input.
Finally, .getline() is one such method of std::cin (and other similar objects). You tell it how many characters it should get from the object on its left side (std::cin here), and where to put those characters. The precise number of characters can vary: .getline() will stop in three cases:
1. The end of a line is reached
2. There are no characters left in the input (doesn't happen normally on std::cin as you can keep typing)
3. The maximum number of characters is read.
There are other methods and functions that can be used with the std::cin object, e.g.
std::string s;
int i;
std::cin >> s; // Read a single word from std::cin
std::cin >> i; // Read a single number from std::cin
std::getline(std::cin, s); // Read an entire line (up to \n) from std::cin
std::cin.ignore(100); // Ignore the next 100 characters of std::cin
In case with char*, std::cin.getline getting line, instead of std::cin getting first word.
Did you read any documentation (e.g. http://www.cplusplus.com/reference/string/getline/)?
Basically, std::cin (or more generally, any std::istream) is used directly in order to obtain formatted input, e.g. int x; std::cin >> x;. std::cin.getline() is used simply to fill a raw char * buffer.
(Very simplefied)My answer is, that std :: cin.getline() can contain spaces, while std :: cin >> can not.
As already others have answered (even better) roughly speaking, use getline() to read an entire line (i.e., a string terminating with \n) and cin>>var to read a number compatible with the type of var (integer, float, double etc.) or a single word.
In this answer I want to emphasize a problem that arises when mixing the two methods. When you do:
int a;
string s;
cin>>a;
getline(cin, s)
cin leaves an end of line, \n, character which is then read by getline();. It is possible to overcome this problem by using cin.ignore().
int a;
string s;
cin>>a;
cin.ignore();
getline(cin, s)
My question seems to be the same as this one, but I didn't find an answer since the original question seems to ask something more specific.
In C++98, what is the difference between
char c;
cin.get(c);
and
char c;
cin >> c;
?
I've checked the cplusplus reference for get and operator>>, and they look the same to me.
I've tried above code and they seem to behave the same when I input a char.
The difference depends on when there is a whitespace character on the stream buffer.
Consider the input ' foo'
char c;
cin.get(c);
Will store ' ' in c
However
char c;
cin >> c;
Will skip the whitespace and store 'f' in c
In addition to what's already been said, std::istream::get() is also an unformatted input function so the gcount() of the stream is affected, unlike the formatted extractor. Most of the overloads of get() and getline() have mostly been made obselete by the introduction of std::string, its stream extractors, and std::getline(). I'd say to use std::istream::get() whenever you need a single, unformatted character straight from the buffer (by using its single or zero argument overload). It's certainly quicker than turning off the skipping of whitespace first before using the formatted extractor. Also use std::string instead of raw character buffers and is >> str for formatted data or std::getline(is, str) for unformatted data.
I have to read huge lines of strings from stdin so time is a critical issue. Strings are on consecutive lines and have no spaces so I can simply use while(cin>>str) { //code } but this is extremely slow. I have heard that scanf is much more faster than cin but if I use scanf("%s,str) I think that str is treated as char* and not a C++ string so I can't use the STL. I could take input as char* and copy all the chars into a C++ string but IMO that will also be slow.
Is there a way to get input using scanf or something but still get a C++ string as a result?
If you know the average or maximum size of the text, you create std::string with a pre-allocated size. One area occupying a lot of time is the memory (re) allocation by std::string.
cin >> str is the closest thing you'll find in STL to scanf("%s, str"). The only reason scanf would be faster than cin is because it would be giving you a char* instead of a string, and while you can create a new string from the char* by just passing them in to the string() constructor, that would be almost the same thing as using cin >> str.
You can use getline:
for (std::string line; getline(std::cin, line); ) {
do_something_with(line);
}
I don't know if it is any faster than cin >> line, but it might be, since it doesn't need to deal with whitespace other than newlines. But I don't believe this is as significant as the overhead of sentry construction.
I am new to C++ . I am writing following simple code. I wanted to pass the character[40] into a function and then get the same as output.
If i put a debug at following point.
strcpy_s(x,100,tester);
But it only takes "This" if i write "This is sent at the output". Can anyone please point out what am i missing and whats the reason for only accepting few characters.
// BUSTesting.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "resource.h"
int testFunction(char* tester);
int _tmain()
{
char m[40];
std::cin>>m;
testFunction(m);
}
int testFunction(char* tester)
{
char x[100] ;
memset(x,100,sizeof(x));
strcpy_s(x,100,tester);
std::cout<<x;
return 0;
}
operator>> will stop consuming input at first whitespace character. An alternative would be to use cin.getline() to prevent processing of input due to whitespace.
Note to initialize an array and avoid memset():
char x[100] = "";
Recommend std::string and std::getline() which avoids specifying a maximum number of characters to read from the input stream (avoiding potential buffer overrun problems with fixed sized arrays).
Change this: std::cin >> m; to this cin.getline(m, 39);
cin >> x doesn't get all line characters until end-line when there is a white-space (space, tab, ...) in the input.
Since you are using C++, it is better to use std::string class instead of old C-style strings.
std::cin>>m probably breaks the string on a space for some reason. Break with a debugger and check m's content. If it's only this, you've found the problem.
When should std::cin.getline() be used? What does it differ from std::cin?
Let's take std::cin.getline() apart. First, there's std::. This is the namespace in which the standard library lives. It has hundreds of types, functions and objects.
std::cin is such an object. It's the standard character input object, defined in <iostream>. It has some methods of its own, but you can also use it with many free functions. Most of these methods and functions are ways to get one or more characters from the standard input.
Finally, .getline() is one such method of std::cin (and other similar objects). You tell it how many characters it should get from the object on its left side (std::cin here), and where to put those characters. The precise number of characters can vary: .getline() will stop in three cases:
1. The end of a line is reached
2. There are no characters left in the input (doesn't happen normally on std::cin as you can keep typing)
3. The maximum number of characters is read.
There are other methods and functions that can be used with the std::cin object, e.g.
std::string s;
int i;
std::cin >> s; // Read a single word from std::cin
std::cin >> i; // Read a single number from std::cin
std::getline(std::cin, s); // Read an entire line (up to \n) from std::cin
std::cin.ignore(100); // Ignore the next 100 characters of std::cin
In case with char*, std::cin.getline getting line, instead of std::cin getting first word.
Did you read any documentation (e.g. http://www.cplusplus.com/reference/string/getline/)?
Basically, std::cin (or more generally, any std::istream) is used directly in order to obtain formatted input, e.g. int x; std::cin >> x;. std::cin.getline() is used simply to fill a raw char * buffer.
(Very simplefied)My answer is, that std :: cin.getline() can contain spaces, while std :: cin >> can not.
As already others have answered (even better) roughly speaking, use getline() to read an entire line (i.e., a string terminating with \n) and cin>>var to read a number compatible with the type of var (integer, float, double etc.) or a single word.
In this answer I want to emphasize a problem that arises when mixing the two methods. When you do:
int a;
string s;
cin>>a;
getline(cin, s)
cin leaves an end of line, \n, character which is then read by getline();. It is possible to overcome this problem by using cin.ignore().
int a;
string s;
cin>>a;
cin.ignore();
getline(cin, s)