字符串操纵和忽略字符串的一部分

String manipulation and ignoring part of string

本文关键字:字符串 一部分 操纵      更新时间:2023-10-16

我使用C

的文本文件中有以下输入

命令1 5 #create 5 box
长度12
插入这是一个盒子

在#sign之后忽略任何内容时,我如何在输入中阅读?

例如,输出应没有#Create 5 Box

command1  5
length    12
insertText THIS IS A BOX

编辑:

我尝试了以下内容:

while(getline(myfile, line))
{
    istringstream readLine(line);
    getline(readLine, command, ' ');
    getline(readLine, input, '');
}

...但似乎不起作用。

外部while(getline(istringsteam很好,但是在此之后,您想将一个分隔式的单词读为命令,然后可能是一个或多个空间分隔的输入,之后:类似的东西

std::string command, input;
std::vector<std::string> inputs;
if (readLine >> command && command[0] != '#')
{
    while (readLine >> input && input[0] != '#')
        inputs.push_back(input);
    // process command and inputs...
}

使用>>getline更容易解析readLine,因为如果他们至少没有一个有效的字符,它们设置了流量故障状态,使[0]索引安全并以空排的方式删除,或者没有输入的命令。

您可以简单地使用std::getline()这样:

int main()
{
    std::ifstream ifs("file.txt");
    std::string line;
    while(std::getline(ifs, line))
    {
        std::istringstream iss(line);
        if(std::getline(iss, line, '#')) // only read up to '#'
        {
            // use line here
            std::cout << line << 'n';
        }
    }
}

输出:

command1 5 
length 12
insertText THIS IS A BOX

在您的函数中,您可以一个一个一个一个字符,添加此代码:(伪代码)

if(currChar == #){
    while(currChar != 'n'){
        getNextChar();// you arent saving it so youre ignoring it
    }
 }else{
    Char c = getNextChar();
    //now you can add this character to your output string

例如。您可以使用忽略(输入size,"#"),也可以使用getlinehttp://www.cplusplus.com/reference/istream/istream/ignore/http://www.cplusplus.com/reference/istream/istream/getline/