gpt4 book ai didi

c++ - 在 g++ 和 msvc 中使用 ifstream 读取文件的差异

转载 作者:太空狗 更新时间:2023-10-29 21:05:21 27 4
gpt4 key购买 nike

当使用 ifstream 类从输入文件中读取单词时,我使用了以下表达式:

 #include <iostream>
#include <fstream>

int main(int argc, char *argv[])
{
std::ifstream inputStream(myFile.txt);
std::string myString;
myFile.open()
while(myFile.good())
{
myFile >> myString;
printf("%s \n", myString);
}
return 0;
}

myFile.txt 的内容是:“这是一个简单的程序。”

使用 g++ 编译器按预期编译和执行。

但是,使用 msvc 2008 编译时,相同的代码会在提取运算符 (>>) 处返回错误,要求我将 std::string 替换为已初始化的字符数组或任何受支持的 native 类型。
这让我失望了,因为我期望标准库的使用在不同的实现中是相同的。
我了解编译错误并知道使用 c_str() 修复它的方法。

但是,如果有人能澄清为什么标准库的使用在不同平台上不同,那将对我有很大帮助。
对我来说,它不再是标准的了!!

编辑:代码已更新为完整。更新了 myFile.txt 的内容。

最佳答案

很可能您忘记了 #include <string> .没有它,微软的版本 <iostream> (等等)包括足够的声明 std::string有些东西可以工作,但其他部分缺失,所以你会遇到奇怪的、看似莫名其妙的失败。

缺少的东西之一是 std::string 的大部分运算符重载。 ,这正是您似乎缺少的。

顺便说一句,while (myfile.good()) ...几乎是一个有保证的错误——你可能想要:

while (myfile>>myString)
std::cout << myString << " \n";

或者,您可以使用标准算法完成这项工作:

#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>
#include <iostream>

int main() {
std::ifstream myfile("input.txt");

std::copy(std::istream_iterator<std::string>(myfile),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, " \n"));
return 0;
}

关于c++ - 在 g++ 和 msvc 中使用 ifstream 读取文件的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10112557/

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