I need to read input from standard input until a space or a TAB is pressed.
Eventually, I need to hold the input in a std::string
object.
I need to read input from standard input until a space or a TAB is pressed.
Eventually, I need to hold the input in a std::string
object.
#include <iostream>
#include <string>
int main()
{
std::string result;
std::cin >> std::noskipws; //don't skip whitespaces
char c;
while (std::cin >> c)
{
if(c == '\t' || c == ' ')
break;
result.push_back(c);
}
}
Since a tab counts as whitespace, you are asking to extract the first token from the stream. This is very easy in C++, as token extraction is already the default behaviour of the >>
operator:
#include <iostream>
#include <string>
int main()
{
std::string token;
if (!(std::cin >> token)) { /* error */ return 1; }
// now you have the first token in "token".
}
(The error can only occur in arcane circumstances, e.g. when the input file descriptor is already closed when the program starts.)
You can use getch()
or getchar()
to read each character separately, and then process the input manually so that when a space or a tab is pressed, you end the input.
You can have std::cin
to stop reading at any designated character using
char temp[100];
std::cin.getline(temp, 100, '\t');
I don't know if you can easily get it to work with two characters though.
This should do the job:
#include <stdio.h>
int main ()
{
char c;
do {
c=getchar();
/** Your code here **/
} while ((c != ' ') && (c != '\t'));
return 0;
}
It seems that the solution to this is, indeed, a lot easier using scanf("%[^\t ]", buffer)
. If you want to do it using C++ IOStreams I think the nicest to use option is to install a std::locale
with a modified std::ctype<char>
facet which uses a modified interpretation of what is considered to be a space and then read a std::string
(see e.g. this answer I gave for a similar problem). Independent of whether you are using a C or a C++ approach you probably need to turn off line buffering on the standard input if you want to find out about the space or the tab when it entered rather than when the entire line is given to your program.
use scanf for this:
A simple code:
#include<iostream>
#include<stdio.h>
int main()
{
char t[1000]={'\0'};
scanf("%[^\t ]",t);
printf("%s",t);
std::string mains(t);
return 1;
}
The simple answer is that you can't. In fact, the way you've formulated the question shows that you don't understand istream
input: there's no such thing as “pressed” in istream
, because there's no guarantee that the input is coming from a keyboard.
What you probably need is curses
or ncurses
, which does understand keyboard input; console output and the rest.