从字符串中删除空格

时间:2017-10-30 01:43:47

标签: c++

我对C ++比较陌生,我正试图弄清楚如何正确编码。我必须读取一个文件,里面有3个变量,用空格分隔:

  Planet      Diameter (miles)  Length of Day (hours)
Mercury          3032             4222.6
Venus            7521             2802.0
Earth            7926               24.0
Jupiter         88846                9.9

在我的代码中,我应该将该行解析为3个变量(行星,直径,长度),回显此数据,然后转换直径和长度。我的问题是我不知道如何正确分配变量的直径和长度,以便它们中没有存储空格,这样我就可以使用stod来执行计算(我认为)。

int main()
{
    //Declare Variables
    string line;
    string planet;
    string diameter;
    string length;

    //Application Header
    cout << "Welcome to Planet Poachers" << endl;
    cout << "--------------------------" << endl;

    //Open file
    ifstream dataIn;
    dataIn.open("PlanetsIn.txt");

    // Open the file and check that it was found and correctly opened
    if (!dataIn)
    {
        cout << "Error finding and opening the data input file.\n";
        exit(1);
    }

    //Read past header
    getline(dataIn, line);

    //Echo data
    while (dataIn.good())
    {
        //getline(dataIn, line);
        cout << fixed << setprecision(1);
        getline(dataIn, line);

        //Assign variables
        planet = line.substr(0, 10);
        diameter = stod(line.substr(11, 21));
        length = stod(line.substr(22, 40));

        //Display data
        cout << "Input line (miles, hours): ";
        cout << planet << diameter << length << endl;
        cout << "Output line (kilometers, days): ";
        cout << planet << (diameter * 1.609344) << (length / 24)
            << endl << endl;

    }

    //Close file
    dataIn.close();

    //End of application
    cout << endl << endl << "End of Application. Press Any Key to Exit.";
    getch();
    return 0;
}

1 个答案:

答案 0 :(得分:2)

问题是你的变量行星,直径和长度都是std :: string。您无法对字符串执行算术运算。您可以将各个字段解析为字符串变量,但是您需要将这些字符串转换为双精度字符串。即。

double dia_dbl = std::stod(diameter);
double len_dbl = std::stod(length);

std::cout << planet << ": " << (dia_dbl * 1.609) << "," << (len_dbl / 24) << std::endl;

std :: stod会丢弃任何前导空格。