c++字符串和char*操作行为怪异
C++ string and char* manipulation acting weird
我不知道这段代码在哪里有缺陷-主要是因为当我在Win7(用MSVS2010编译)下运行。exe时它工作得很好,但它在Ubuntu(用g++编译)下不起作用
以下是有问题的片段:
char * context = nullptr;
ifstream input("file.txt");
string line;
while(getline(input, line)) {
char * line1 = new char[line.size() + 1];
copy(line.begin(), line.end(), line1);
line1[line.size()] = ' ';
char * token = strtok_r(line1, " ", &context);
if(labela(token))
cout << "yes";
else
cout << "no";
// ...
token = (nullptr, " ", &context);
}
// ...
这是标签(…)
bool labela(char * c) {
if(c == nullptr)
return false;
int i = 0;
while(c[i] != ' ')
++i;
if(c[--i] == ':')
return true;
return false;
}
这是怎么回事?我不知道为什么它有时能识别标签,有时不能。
以下是它应该识别标签的行示例:
label: 剩余行
或
label:
下一行
有时使用c++自己的字符串函数比使用C的字符串函数更好。
要获取字符串的第一个单词,您可以简单地使用substr()
:
char* context = 0;
ifstream input("file.txt");
string line;
while(getline(input,line)) {
// char* line1 = new char[line.size()+1];
// copy(line.begin(),line.end(),line1);
// line1[line.size()] = ' ';
// char* token = strtok_r(line1, " ", &context);
string token = line.substr(0, line.find(" "));
if(labela(token))
cout << "yes";
else
cout << "no";
...
您仍然可以使用labela()
:
bool labela(string c) {
if (c.empty())
return false;
...
相关文章:
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 字符串操作 - 字符计数
- 在 c++ 中对字符串进行操作的关系运算符无法按预期工作
- 字符串操作主题消息
- std::字符串串联操作
- 在MySql中使用字符串操作函数有什么问题
- 如何在没有外部库的情况下使用C++03约束执行基于正则表达式的字符串操作
- 使用来自串行端口的字符串数据来操作振镜扫描仪在更高的速度下会出错
- 如何使用 Win32 WCHAR 执行字符串操作
- C 库中是否有任何功能将字符串转换为算术操作
- 如何将字符 a= '+'(或字符串 []) 变成实际操作?
- UTF-8字符串上的位XOR操作可提供非UTF-8输出
- 一个用于操作字符串以在vba中使用的c++dll
- 操作字符串的函数 ( "abcdef" -> "faebdc" )
- 操作字符串c++
- c++:通过函数使用指针操作字符串
- 通过对dll的标准调用操作字符串的问题
- 如何操作字符串小写并存储在同一变量中
- 使用fork() c++在共享内存中操作字符串