gpt4 book ai didi

c++ - 为什么我的 if 语句会出现段错误?

转载 作者:行者123 更新时间:2023-11-27 22:48:01 24 4
gpt4 key购买 nike

我想读取一个文件并计算字数。我想设置它以便我可以使用命令行,或者如果没有在命令行上输入文件,则触发一个 if 语句,该语句将获取文件名并读取它,然后计算字数。如果我在命令行中输入文件名,它就可以工作,但是如果我不使用它,它就会出现段错误。这是代码:

int main(int argc, char **argv)
{
char file[75];
if (argc < 2)
{
cout << "Please enter the filename: ";
cin >> file;
strcpy(argv[1], file);
}
string content;
ifstream inFile(argv[1]);
int count = 0;
while (inFile >> content)
count++;
inFile.close();
display(count, argv);
return 0;
}

最佳答案

你不应该修改 argv 的数据,尤其是越界。你的逻辑应该相反:

   char file[75];
if (argc < 2)
{
cout << "Please enter the filename: ";
cin >> file;
} else
strcpy( file, argv[1] );
string content;
ifstream inFile(file);

但是您最好也将 std::string 用于变量 file

另外 cin >> 只输入单词(不包括空格符号)但文件名可以有它们,所以你最好使用 cin.getline( file )std::getline( cin, file ) 如果将 file 更改为 std::string

关于c++ - 为什么我的 if 语句会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41066869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com