C++ 尝试从istream存储令牌时出现分段错误
我的代码在读取文件时崩溃(见本文末尾)。我在main中声明了一个ifstream对象,将其传递给buildGraph函数(将ifstream&作为参数),并尝试将第一个令牌传递给字符串temp 主设备的相关代码:C++ 尝试从istream存储令牌时出现分段错误,c++,input,io,fstream,C++,Input,Io,Fstream,我的代码在读取文件时崩溃(见本文末尾)。我在main中声明了一个ifstream对象,将其传递给buildGraph函数(将ifstream&作为参数),并尝试将第一个令牌传递给字符串temp 主设备的相关代码: #include <fstream> int main() { ifstream infile1("data31.txt"); if (!infile1) { cout << "File could not be opene
#include <fstream>
int main() {
ifstream infile1("data31.txt");
if (!infile1) {
cout << "File could not be opened." << endl;
return 1;
}
GraphM G;
G.buildGraph(infile1);
}
(包括注释作为允许代码格式设置的答案)
为了构建一个文件,我将所有代码包含在一个文件中,如下所示:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
class GraphM {
public:
void buildGraph(ifstream& input);
};
void GraphM::buildGraph(ifstream& input)
{
string temp;
input >> temp;
cout << temp;
}
int main() {
ifstream infile1("data31.txt");
if (!infile1) {
cout << "File could not be opened." << endl;
return 1;
}
GraphM G;
G.buildGraph(infile1);
}
#包括
#包括
#包括
使用名称空间std;
类图{
公众:
void buildGraph(ifstream和input);
};
void GraphM::buildGraph(ifstream和input)
{
字符串温度;
输入>>温度;
不能包含
#包括
#包括
使用名称空间std;
void buildGraph(ifstream和input)
{
字符串温度;
对于(int i=0;i>temp;
coutw导致崩溃的确切行是什么?是不是input>>temp
?是否有任何错误消息?导致崩溃的行是input>>temp
。错误消息只是“分段错误”当我运行程序时。没有编译错误或警告。你的调试器对此有何评论?显示其回溯。这更多的是一个注释而不是答案。是的,这几乎就是我的代码。:|我在校园的linux机器上使用g++编译器。我在Windows 8上,我的IDE是Visual Studio 2012,但这不应该是我的关于这是为什么,我们需要改变crashing@user2844013:您应该能够在VS2012和Linux G++编译器上编译相同的代码,并得到完全相同的结果——即,使用上面的代码,您在任何情况下都不应该得到分段错误。您得到相同的结果(分段错误)吗对于这两个编译器?如果是这样,你能提供一个产生分段错误的SSCCE吗?鉴于我上面的代码没有产生错误(在我的计算机和编译器上,但你的编译器如何?),代码中一定有你没有向我们展示的东西导致了问题。这并不能回答问题。
5
Aurora and 85th
Green Lake Starbucks
Woodland Park Zoo
Troll under bridge
PCC
1 2 50
1 3 20
1 5 30
2 4 10
3 2 20
3 4 40
5 2 20
5 4 25
0 0 0
3
aaa
bbb
ccc
1 2 10
1 3 5
2 3 20
3 2 4
0 0 0
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
class GraphM {
public:
void buildGraph(ifstream& input);
};
void GraphM::buildGraph(ifstream& input)
{
string temp;
input >> temp;
cout << temp;
}
int main() {
ifstream infile1("data31.txt");
if (!infile1) {
cout << "File could not be opened." << endl;
return 1;
}
GraphM G;
G.buildGraph(infile1);
}
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void buildGraph(ifstream& input)
{
string temp;
for(int i=0; i<sizeof(input); i++)
{
input >> temp;
cout<< temp;
}
}
int main()
{
ifstream infile1("test.txt");
if (!infile1)
{
cout << "File could not be opened." << endl;
return 1;
}
buildGraph(infile1);
}