我的代码有什么问题? (C++ if else 数据结构)
what's wrong with my code? ( C++ if else with datastructures )
我正在使用 C++ 研究数据结构。一切看起来都不错。这是一个简单的 C++ 文件读取。我认为这段代码的输出应该是:
1
K
3
4
5
但我看到了:
1
2
3
4
5
如何在 if
中使用 data[4]
?
这是file.txt
A(1#Jordan)
A(2#Kyrie)
A(3#Lebron)
A(4#Harden)
A(5#Doncic)
这是我的代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream file;
file.open("file.txt", ios::in);
if(file.is_open()){
while(!file.eof())
{
char data[20];
file >> data;
if(2 == data[2])
cout << data[4]<< endl; //**
else
cout << data[2] << endl;
}
}
file.close();
return 0;
}
您将 char 与 int 进行比较的方式存在一个小错误;正确的比较是使用 '2':
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream file;
file.open("file.txt", ios::in);
if(file.is_open()){
while(!file.eof())
{
char data[20];
file >> data;
if('2' == data[2])
cout << data[4]<< endl; //**
else
cout << data[2] << endl;
}
}
file.close();
return 0;
}
我正在使用 C++ 研究数据结构。一切看起来都不错。这是一个简单的 C++ 文件读取。我认为这段代码的输出应该是:
1
K
3
4
5
但我看到了:
1
2
3
4
5
如何在 if
中使用 data[4]
?
这是file.txt
A(1#Jordan)
A(2#Kyrie)
A(3#Lebron)
A(4#Harden)
A(5#Doncic)
这是我的代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream file;
file.open("file.txt", ios::in);
if(file.is_open()){
while(!file.eof())
{
char data[20];
file >> data;
if(2 == data[2])
cout << data[4]<< endl; //**
else
cout << data[2] << endl;
}
}
file.close();
return 0;
}
您将 char 与 int 进行比较的方式存在一个小错误;正确的比较是使用 '2':
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream file;
file.open("file.txt", ios::in);
if(file.is_open()){
while(!file.eof())
{
char data[20];
file >> data;
if('2' == data[2])
cout << data[4]<< endl; //**
else
cout << data[2] << endl;
}
}
file.close();
return 0;
}