我在使用以下函数时遇到了一个奇怪的问题:在某个点之后返回一个包含所有字符的字符串:
string after(int after, string word) {
char temp[word.size() - after];
cout << word.size() - after << endl; //output here is as expected
for(int a = 0; a < (word.size() - after); a++) {
cout << word[a + after]; //and so is this
temp[a] = word[a + after];
cout << temp[a]; //and this
}
cout << endl << temp << endl; //but output here does not always match what I want
string returnString = temp;
return returnString;
}
Run Code Online (Sandbox Code Playgroud)
问题是,当返回的字符串是7个字符或更少时,它的工作方式与预期的一样.当返回的字符串是8个字符或更多字符时,它会在预期输出结束时开始喷出废话.例如,线条
cout << after(1, "12345678") << endl;
cout << after(1, "123456789") << endl;
Run Code Online (Sandbox Code Playgroud)
给出一个输出:
7
22334455667788
2345678
2345678
8
2233445566778899
23456789?,?D~
23456789?,?D~
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能解决这个错误,有没有可以为我做这个的默认C++函数?
使用std :: string :: substr库函数.
std::string s = "12345678";
std::cout << s.substr (1) << '\n'; // => 2345678
s = "123456789";
std::cout << s.substr (1) << '\n'; // 23456789
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1138 次 |
| 最近记录: |