尝试拆分C++字符串,但不断收到错误R6010

Trying to split a string in C++ but keep getting error R6010

本文关键字:错误 R6010 拆分 C++ 字符串      更新时间:2023-10-16
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(,这会引发您抱怨的运行时异常。