【发布时间】:2021-11-25 05:02:33
【问题描述】:
我的程序遇到了问题。总体而言,该程序的基础是从文件中读取有关学生的输入。这包括他们的姓名、身份证、作业成绩和考试成绩。然后应该计算所有分数并产生一个字母等级。我目前只在打印姓名和身份证。我的问题是我的所有变量都出现错误,说它们没有在这个范围内声明。我还收到有关我的字符串类型不匹配的警告(不知道这意味着什么)。范围内未声明错误示例:
part1.cpp:38:2: error: ‘infile’ was not declared in this scope
infile.open (out);
^
part1.cpp:38:15: error: ‘out’ was not declared in this scope
infile.open (out);
类型不匹配警告:
part1.cpp:11:15: note: mismatched types ‘std::basic_ostream<_CharT, _Traits>’ and ‘int’
outfile << name << " "
^
In file included from /usr/include/c++/4.8.2/string:52:0,
from /usr/include/c++/4.8.2/bits/locale_classes.h:40,
from /usr/include/c++/4.8.2/bits/ios_base.h:41,
from /usr/include/c++/4.8.2/ios:42,
from /usr/include/c++/4.8.2/ostream:38,
from /usr/include/c++/4.8.2/iostream:39,
from part1.cpp:1:
这里是整体代码:
#include <iostream>
#include <fstream>
#include <string>
void printOutput (std::string name, std::string Id, float HPfinalscore, float testFinalscore,
float overallScore, string LetterGrade, ostream& outfile)
{
outfile << name << " "
<< Id << " ";
/*
<< HPfinalscore << " "
<< testFinalscore << " "
<< overallScore << " "
<< LetterGrade;
*/
}
int main()
{
ofstream outfile;
ifstream infile;
int num;
std::string file_name;
std::string name;
std::string Id;
std::string LetterGrade;
float HPfinalscore = 0, testFinalscore=0, overallScore=0;
std::cout<<"How many files are you processing: ";
cin>>num;
infile.open (out);
for(int i=0;i<num;i++)
{
int count[10];
for(int i=0;i<10;i++)
count[i]=0;
char c,s[1000];
std::cout<<"Please input the name of the file: ";
cin>>file_name;
infile.open(file_name.c_str());
if ( !infile)
{
continue;
return 0;
}
outfile.open("Result");
if ( !outfile)
{
std::cout << "Could not open output file \n";
return 0;
}
infile >> name;
while(!infile.eof())
{
infile >> Id;
/*
HPfinalscore = getHPScores(infile);
testFinalscore = getTestscores(infile);
overallScore = EndingScore(HPfinalscore, testFinalscore);
LetterGrade= Grade(overallScore);
*/
printOutput (name, Id, HPfinalscore, testFinalscore, overallScore,
LetterGrade, outfile);
infile >> name; //try to read another name
}
infile.close();
outfile.close();
return 0;
}
}
所以我的问题是如何正确声明我的变量?此外,任何有关警告的信息以及如何处理它都将不胜感激。
【问题讨论】:
-
ifstream infile;应该是std::ifstream infile;outfile相同。 -
你应该从第一个错误开始:godbolt.org/z/1bdaGTf6f
-
您对
std::前缀的看法不一致。string应该是std::string和ostream应该是std::ostream(以及 Johnny Mopp 所说的ifstream和ofstream)。 -
infile.open()的参数应该是一个字符串,而是未声明的变量out。 -
@ChunkierLizard 你的编译器应该给你所有这些错误。请务必阅读编译器的输出。
标签: c++ string error-handling scope