2

所以这是一个简单的问题。只需从特定文件中读取输入。使用输入作为摄氏温度并将此温度转换为华氏温度,然后将结果打印给用户。

当我尝试保存文件中的输入时,似乎出现了问题。位于 while 块中。我收到一个错误,我知道这可能是由于尝试在 getline 中使用 int 值引起的。我对 c++ 相当陌生,不知道如何做到这一点。我尝试了无数种方法,但似乎都没有奏效。任何帮助将不胜感激!

我做到了#include <fstream>

该文件包含这三个值“0 50 100”。

这是我一直在使用的代码部分:

//values for the files three input values
int i = 0, inVal1 = 0 , inVal2 = 0, inVal3 = 0,
    farenheit1 = 0, farenheit2 =0,farenheit3 = 0; 

ifstream inFile; //Input file variable


inFile.open("celsius_input.dat"); //open the file

if(!inFile){
    cout << "Unable to open file";
    exit(1); //terminate with error
}//end if
while (inFile)
{
    cin.ignore();
    getline(inFile, inVal1);
    getline(inFile, inVal2);
    getline(inFile, inVal3); // read the files values

    inFile.close();//Close file


} //end while       



farenheit1 = (9.0/5.0) * inVal1 + 32.0; //formula 
farenheit2 = (9.0/5.0) * inVal2 + 32.0; //formula
farenheit3 = (9.0/5.0) * inVal3 + 32.0; //formula


cout << "The first Inputed Value, " << inVal1
    << " degrees, Converted Into Farenheit Is "
    << farenheit1 << " Degrees!" << endl; //output of results
cout << "     " << endl;

cout << "The Second Inputed Value, " << inVal2
    << " degrees, Converted Into Farenheit Is "
    << farenheit2 << " Degrees!" << endl; //output of results
cout << "     " << endl;

cout << "Teh Third Inputed Value, " << inVal3
    << " degrees, Converted Into Farenheit  Is "
    << farenheit3 << " Degrees!" << endl; //output of results
cout << "     " << endl;
4

2 回答 2

1

我建议最简单的方法是:

#include <fstream>
#include <iostream>

int main()
{
    std::ifstream inFile("celsius_input.dat"); //open the file

    double celsius;
    while (inFile >> celsius)
    {
        double fahrenheit = (9.0/5.0) * celsius + 32.0;
        std::cout << "The input value " << celsius << " degrees, converted into fahrenheit is " << fahrenheit << " degrees" << std::endl;
    }
}

如果您确实必须先阅读一行,请执行以下操作:

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

int main()
{
    std::ifstream inFile("celsius_input.dat"); //open the file

    std::string input;
    while (std::getline(inFile, input))
    {
        double celsius = std::strtod(input.c_str(), nullptr);
        double fahrenheit = (9.0/5.0) * celsius + 32.0;
        std::cout << "The input value " << celsius << " degrees, converted into fahrenheit is " << fahrenheit << " degrees" << std::endl;
    }
}
于 2013-06-02T20:46:43.377 回答
0

您正在使用的 std::getline 函数将输入保存到字符串(请参阅:http ://www.cplusplus.com/reference/string/string/getline/ )。如果您传递给函数的参数是一个字符串,它将从您的文件中获取整行,即“0 50 100”并将其放入您的字符串中。

您可以尝试将其保存为字符串,然后将其拆分为三个部分并在 C++11 中使用 atoi 或 std::stoi 转换为整数(检查Convert string to int C++) - 这样可能更容易处理错误。

但是有一种更简单的方法可以做到这一点 - 假设您的数字被空格分隔并且几乎所有内容都正确,“>>”运算符会在空格上中断。尝试:

inFile >> inVal1;
inFile >> inVal2;
inFile >> inVal3;

此外,在使用 inFile 缓冲区时不需要使用 cin.ignore()。每个流都有一个与之关联的不同缓冲区(和 cin != inFile),因此您无需清除 cin 缓冲区即可从文件中读取。

于 2013-06-02T20:57:14.993 回答