尝试拆分C++字符串,但不断收到错误R6010
Trying to split a string in C++ but keep getting error R6010
void piglatin(string str)
{
string temp = str; //copies the string passed to the function into temp.
temp = temp + str.at(0); //adds the first character of the word to the end of the word.
temp = temp.erase(0, 1); //deletes the first character from the temp string.
temp = temp + "AY"; //adds "AY" to the temp string
cout << temp << " "; //prints out the word followed by a space.
}
string userIn("I NEED THIS IN PIG LATIN");
istringstream iss(userIn);
do
{
string sub;
iss >> sub;
piglatin(sub);
} while (iss);
所以我正在尝试使用此方法将字符串拆分为 C++但我不断收到错误,但程序会执行我想要它做的事情。我只需要摆脱错误R6010。
您的代码基本上没问题,只是您错误地检查了文件结尾(或在这种情况下为字符串结尾(,这导致将空字符串发送到piglatin()
,导致str.at(0)
异常。
你可以用这样的东西来解决这个问题(包括使代码成为一个完整的可行程序(:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void piglatin(string str) {
string temp = str;
temp = temp + str.at(0);
temp = temp.erase(0, 1);
temp = temp + "AY";
cout << temp << " ";
}
int main () {
string userIn("I NEED THIS IN PIG LATIN");
istringstream iss(userIn);
string sub;
while (iss >> sub)
piglatin(sub);
cout << 'n';
return 0;
}
然后你得到的输出是:
IAY EEDNAY HISTAY NIAY IGPAY ATINLAY
我认为猪拉丁语并不完全正确(我似乎记得单词以元音开头的规则略有不同,您必须将辅音组移到末尾而不仅仅是第一个(,但如有必要,我会让你解决这个问题。
就循环的工作原理而言:
while (iss >> sub)
piglatin(sub);
这只会一直持续到项目(在本例中为单词(的提取失败。幼稚的代码(我会坦率地承认我犯了罪(会使用这样的东西:
do {
string sub;
iss >> sub;
piglatin(sub);
} while (!iss.eof());
但这并没有考虑到即使提取失败,您也可能不在文件末尾的事实,例如,如果您的短语末尾有一个空格,或者如果您在流中的下一个标记是非整数时扫描整数。
而且,顺便说一句
,实际上没有必要单独执行piglatin()
中的所有操作,也不需要(显式(临时字符串。您可以将整个批次替换为:
void piglatin (string str) {
cout << str.substr(1) + str.at(0) + "AY ";
}
如果您打算切换到"适当的"Pig Latin,因为它可能更复杂,或者如果这是一项任务并且您不需要成为C++专家,那么将其保留为单独的操作可能是值得的:-(
...由于第一个答案中提到的错误,您的代码最终会调用 piglatin(( 传递一个空字符串。
此时,str.at(0( 会导致明显的未定义行为(完全为空的字符串中没有字符 #0(,这会引发您抱怨的运行时异常。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- std ::线程导致应用程序中止错误R6010
- 调试错误.已调用R6010中止()
- 调试错误R6010-已调用abort()
- 什么是 R6010 错误
- 提升 asio、shared_from_this() 错误 R6010 和 async_read() eof
- 错误 R6010.为什么叫它
- 尝试拆分C++字符串,但不断收到错误R6010
- 调试错误r6010已在C++中调用Abort
- Substral()运行时错误:已调用R6010中止
- QT调试错误r6010中止在完全运行时被调用
- 调试错误R6010
- R6010使用错误;std:: stoi