从fstream读取输入

Reading input from fstream

本文关键字:输入 读取 fstream      更新时间:2023-10-16

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

当我试图从文件中保存输入时,问题似乎发生了。位于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;

我建议最简单的方法是:

#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;
    }
}

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

您可以尝试将其保存为字符串,然后将其分成三个部分,并在c++ 11中使用atoi或std::stoi转换为整型(检查将字符串转换为整型c++) -这种方式将更容易处理可能的错误。

但是有一种更简单的方法——假设你的数字是由空格分割的,并且几乎所有的东西都是正确的,">>"运算符会在空格上中断。试一试:

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

同样,在使用inFile缓冲区时也不需要使用cin.ignore()。每个流都有一个与之相关联的不同缓冲区(和cin != inFile),所以你不需要清除cin缓冲区来从文件中读取。