gpt4 book ai didi

c++ - 字符串重排 C++

转载 作者:行者123 更新时间:2023-11-28 03:38:59 24 4
gpt4 key购买 nike

我正在拉取一个文本文件 - 它将由用户输入目前它只是从 C:\Dump\test.txt 中提取我想重新排列所述文件中的单词

这是我目前的情况

static string revFunc(string a)
{
ifstream inp;
inp.open(a, std::ios::in);
string lines;

while(getline(inp, lines)){
istringstream iss(lines);
string outstr;
string word;
iss >> outstr;
if (inp >> word){
outstr = word + ' ' + outstr + ' ';
cout << outstr;

}
}return 0;
}

字符串a是硬盘上文件的路径这将向后解析 2 行测试文件中有 ~13 行

这是来自 int main()

int main(){
string file;
int words = 0;
int lines = 0;
int choice;

system("cls");

cout << "Enter Filename: " << endl;
file = "C:\\Dump\\test.txt";
cout << file;
//cin >> file;

cout <<"MENU"<<endl;
cout <<"----------------------------------" << endl;
cout << "1. Count Words" << endl;
cout << "2. Count Lines" << endl;
cout << "3. Index Words" << endl;
cout << "4. Average Length of Words" << endl;
cout << "5. Print Text File to Screen" << endl;
cout <<"----------------------------------" << endl;
cout << "??: ";
cin >> choice;

switch(choice){

case 1: cout << "Words: " << wordFunc(file) << endl;
system("PAUSE");
break;
case 2: cout << "Lines: " << lineFunc(file, lines) << endl;
system("PAUSE");
break;
case 3: indexFunc(file);
system("PAUSE");
break;
case 4: cout << "Average Length: " << avgWordFunc(file) << endl;
system("PAUSE");
break;
case 5: printStrFunc(file);
cout <<endl;
system("PAUSE");
break;
case 6: revFunc(file);
cout << endl;
system("PAUSE");
break;

}

return 0;
}

然后程序中止 - 我确定是由于错误的编码 :)感谢任何指出我荒谬错误的帮助

最佳答案

你说你的 refFunc 返回一个 string,但返回值是 0(一个 int,不是字符串).

这将导致问题,因为程序尝试使用字符串对象,并发现“垃圾”(已分配以预期字符串但未填充字符串的正确位)。

要修复,您需要将返回值 type 更改为 int 或将返回值 value 更改为有效字符串(例如 "").

或者,如果您不使用返回值(如示例中的情况),则可以将返回类型更改为 void。在这种情况下,只使用return;(注意:return 后没有值),或者你可以把整个return 语句都去掉;

注意:为防止将来出现此类错误,请将编译器配置为使用最大警告设置进行编译,并可能将警告转化为错误。这将防止您在编译器至少没有告诉您您正在做某事(很可能)不正确的情况下编译您的程序

注意:即使是暂停应用程序,也不要养成使用 system() 的习惯。它依赖于平台,并且会带来安全风险(尽管我认为您暂时不会担心)

关于c++ - 字符串重排 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9940803/

24 4 0
文章推荐: css - 在 WordPress 子主题中覆盖 FLTheme 类函数
文章推荐: twitter-bootstrap - 使用字体大小更改