【问题标题】:Compiling Errors with Arrays and 'struct'?使用数组和“结构”编译错误?
【发布时间】:2014-11-27 21:37:48
【问题描述】:

我的第一节编程课(第一节编程课)即将结束,我需要帮助我编写代码,看看我是如何弄不清楚编译错误的。

首先,我尝试加载的数组给我带来了问题。

string stu[15];
stu[0]= Billy;
stu[1]= Bobby;
stu[2]= Bailee;
stu[3]= Barney;
stu[4]= Bambi;
stu[5]= Barbie;
stu[6]= Barrie;
stu[7]= Barry;
stu[8]= Benny;
stu[9]= Barkley;
stu[10]= Bennie;
stu[11]= Bonnie;
stu[12]= Bernie;
stu[13]= Bertie;
stu[14]= George;

显然它说每一个都是未声明的。但我认为这几乎是数组的重点?不要把所有的时间都花在声明变量上?

我的另一个问题是这段代码......

int name_count = 0;

while (name_count < 15) 
{ 
    inputFile >> (stu[0]); 
    if (!inputFile.good()) break; 
    ++name_count; 
}

我正在尝试将 .txt 文件中的数据加载到数组中,但我对如何执行此操作感到困惑。

所有代码放在一起:

#include <iostream>
#include <fstream>
#include <cmath>
#include <string>

using namespace std;

int main() {
    string inputFile;
    string stu[15];
    stu[0] = Billy;
    stu[1] = Bobby;
    stu[2] = Bailee;
    stu[3] = Barney;
    stu[4] = Bambi;
    stu[5] = Barbie;
    stu[6] = Barrie;
    stu[7] = Barry;
    stu[8] = Benny;
    stu[9] = Barkley;
    stu[10] = Bennie;
    stu[11] = Bonnie;
    stu[12] = Bernie;
    stu[13] = Bertie;
    stu[14] = George;

    ofstream(studentFile)("Students.txt");
    studentFile.open("Students.txt");

    studentFile << " STUDENT INFO HERE ";
    studentFile.close();

    int name_count = 0;

    while (name_count < 15) {
        inputFile >> (stu[0]);
        if (!inputFile.good())
            break;
        ++name_count;
    }

    system("pause");
    return 0;
}

我不断收到编译错误:

'inputFile >> stu[0]'中的'operator>>'不匹配

'struct std::string' 没有名为 'good' 的成员

很确定我在这里遗漏了一些东西......任何帮助都将不胜感激。非常感谢。

【问题讨论】:

  • 不要给我们带来编程课作业。

标签: c++ arrays compilation


【解决方案1】:

'inputFile >> stu[0]'中的'operator>>'不匹配

您不能将 > 与字符串一起使用。

inputFile 是 std::string 类型,并且 有任何成员函数 good()。您可能打算使用输入文件流 (ifstream)。

另外,避免使用system() 调用。

【讨论】:

    【解决方案2】:

    你忘记用""包裹你的字符串

    "Bernie"
    

    C++ 目前你正试图将你的结构分配给对象BillyBobby 等等……等等……

    这是因为 C++ 需要显式类型声明,编译器并不隐式知道 Billy 应该是字符串而不是对象。您需要使用"Billy 来表示字符串类型。

    【讨论】:

      猜你喜欢
      • 2011-05-20
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 2023-03-14
      相关资源
      最近更新 更多