gpt4 book ai didi

c++ - 从文件中捕获和转换字符串并执行数值运算

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

这是我的代码:

int main()
{
std::ifstream myfile;
myfile.open("ex.txt");
std::string a;
while(myfile.eof()!=1)
{
getline(myfile,a,',');
int i = stoi(a);
if (!(i%2))
std::cout<<a<<std::endl;
}

}

基本上我有一个用逗号分隔的整数的文本文件。我现在甚至希望显示这些整数。我在 Xcode 上运行代码,Apple LLVM。我得到了正确的输出,但 Xcode 显示了一些奇怪的异常:

libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion Program ended with exit code: 0

此消息在 stoi 命令上带有一个断点。发生了什么?我怎样才能顺利地做到这一点?

编辑:输入文本文件。

5,8,4,8,0,8,4,3,0,7,8,3,6,2,9,7,3,0,9,0,1,9,2,4,5,4,9,8,4,3,0,9,3,3,5,1,1,8,6,3,4,6,8,2,0,2,6,2,1,6,6,1,9,4,1,1,2,9,3,0,3,2,3,9,4,8,0,3,2,2,6,9,1,1,8,1,0,3,6,3,0,3,2,8,6,5,0,3,7,4,3,3,6,0,1,2,2,8,2,5,1,0,0,2,8,8,3,3,8,9,2,3,6,2,5,0,2,4,6,2,6,1,0,2,6,7,1,2,1,8,5,2,2,3,4,2,7,1,7,3,3,8,9,3,2,9,9,5,1,3,4,2,2,0,1,3,0,8,3,4,7,4,5,5,6,4,0,7,8,0,1,1,8,5,2,7,4,4,6,3,4,4,8,3,4,1,1,1,9,2,5,1,3,4,2,6,4,8,7,2,

没有 \n 即换行

最佳答案

我相信这与您正在使用 while (!eof()) 这一事实有关。这是用作条件的错误表达式,因为它不符合 IOStreams 的预期功能。您应该在执行输入之前检查输入是否成功:

while (std::getline(myfile, a, ','))

否则会导致流到达文件末尾并且字符串 a 没有值。然后将此空字符串传递给 std::stoi,导致抛出异常。

关于c++ - 从文件中捕获和转换字符串并执行数值运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21022078/

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