字符串操纵和忽略字符串的一部分
String manipulation and ignoring part of string
我使用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/
相关文章:
- C++:如何使函数只返回作为列表一部分的字符串
- 如何将字符串的一部分转换为整数
- 如何有效地将一个大std::字符串的一部分转换为float
- 需要从字符串数组的一部分访问元素
- 当 NUL 字符被定义为字符串的一部分时,为什么 strlen() 不计算终止 NUL 字符的字节?
- 如何正确实现 std::all_of 函数来验证字符串的一部分?
- boost::async_write 跳过字符串的一部分
- 如何在不复制的情况下比较字符串的一部分?
- 我如何在QT中获得字符串的一部分
- 如何在C++中比较数组中字符串的一部分的字符串
- 如何在 c++ 中拆分字符串的一部分
- 字符数组仅占用字符串的一部分
- 如何用双C 替换字符串的一部分
- 如何在字符串中选择句子的一部分 (C++)
- 如何拆分 QString 并将一部分字符串保存在浮点数的向量中
- 为什么C 正则只能找到JavaScript Regex在字符串中找到的一部分
- 字符串操纵和忽略字符串的一部分
- 在C 中更新字符串的一部分
- 有条件地确定字符串是否是数组的一部分
- 尝试在 Cocos2d-X C++中设置一个带有整数作为其字符串一部分的 CCLabelTTF