How do I read input from standard input until a sp

2020-07-22 19:10发布

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.

标签: c++
8条回答
何必那么认真
2楼-- · 2020-07-22 19:27

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.

查看更多
孤傲高冷的网名
3楼-- · 2020-07-22 19:31

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.

查看更多
我想做一个坏孩纸
4楼-- · 2020-07-22 19:36

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.

查看更多
放我归山
5楼-- · 2020-07-22 19:46
#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);
    }

}
查看更多
你好瞎i
6楼-- · 2020-07-22 19:46

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;

}
查看更多
Root(大扎)
7楼-- · 2020-07-22 19:47

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.)

查看更多
登录 后发表回答