【问题标题】:what's wrong with my code? ( C++ if else with datastructures ) [closed]我的代码有什么问题? (C++ if else with datastructures)[关闭]
【发布时间】:2021-11-06 10:08:34
【问题描述】:

我正在使用 C++ 研究数据结构。一切看起来都很好。这是一个简单的 C++ 文件读取。我认为这段代码的输出应该是:

1
K
3
4
5

但我看到了:

1
2
3
4
5

如何将data[4] 带入if

这是文件.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;                                                                     
}

【问题讨论】:

  • 您将 characters 读入数组 data。我不知道2 == '2' 的任何字符编码。
  • @Someprogrammerdude 谢谢你的回答,我会查的。
  • 扩展一些程序员老兄的评论 - 没有(零,零)标准化数据集2 == '2'。即使有这样的字符集,所有 C++(和 C)标准都要求实现将字符 '0''9' 作为连续集(即 '1' == '0' + 1'2' == '1' + 1 等)和 @987654337 @ 不能有零数值
  • 请查看How to Ask。你的问题标题太模糊了。

标签: c++ data-structures


【解决方案1】:

在将 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;                                                                     
}

【讨论】:

猜你喜欢
  • 2021-10-22
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 2019-03-18
相关资源
最近更新 更多