繁体   English   中英

我如何将用户输入拆分为同一个 function 中的字符串和 integer 值并分别返回它们。 c++

[英]How do i split up user input into both string and integer values in the same function and return them both separately. c++

我是 c++ 的新手,正在尝试一项小任务。 我一直在弄清楚如何拆分 integer 和来自用户输入的字符,并将这两个值返回给调用者。 我知道函数只能返回一个值,所以我尝试使用结构创建两个变量,然后询问用户输入并将其拆分,但它无法得到任何结果。 有没有更简单的解决方案,请记住我有意为所有单独的部分创建单独的功能?

目标是从一行中获取用户的输入,拆分文本以便我们知道 integer 值和温度,返回这些值,然后使用另一个 function 进行转换,另一个进行打印,等等。

这是代码:

#include "TempHead.h"

#include  <iostream>


int main(){

    int x {readCharInput()};
    int y{readTempInput()};
    int g{Converter(x,y)};

    Print(g);

    return 0;
}



void Print(int x){
    std::cout << "Your converted temperture is: " << x;
}


#if 0

struct foo(){

    int x{};
    char y{};
    

}


foo temp(){


}

 #endif

int readTempInput(){

    std::string x{};
    std::string y{};

    std::cout << "Please enter the tempertaure you would like to convert in format (int/char): ";

    std::getline(std::cin, x, '/');
    std::getline(std::cin, y, '/');
 

    return x, y;

}


int Converter(char x, int y){

    int Conv{};

    if(x == 'C'){
        Conv = (y - 32) * 0.5556;

    }else if (x == 'F')
    {
        Conv = y * 1.8 + 32;
    }
    
    return Conv;
}

这就是我试图用 struts 做的事情,我不完全理解所以我试了一下但无法让它工作。

struct readTemp{

    int value{};
    char y{};
    

};


readTemp tempRead(){


     std::string x{};
     std::string y{};

    std::cout << "Please enter the tempertaure you would like to convert in format (int/char): ";

    std::getline(std::cin, x, '/');
   //std::getline(std::cin, y, '/');
    std::cin >> y;
 

    readTemp read = {x,y};
    
    return read;

}

readTemp read = {x,y}; 要求x r 是一个inty是一个char 它们都是std::string

一个可能的解决方案:

readTemp tempRead(){


     std::string x{};
     std::string y{};

     std::cout << "Please enter the temperature you would like to convert in format (int/char): ";

     std::getline(std::cin, x, '/');
     std::getline(std::cin, y); // assuming user input will be ended by the user hitting enter.
 

    readTemp read = {
        std::stoi(x), // convert to int. Exception on failure
        y.size()==1? // if y is exactly 1 character
            y[0]: // provide that one character
            throw std::runtime_error("didn't get a character")}; // exception on failure
    
    return read;
}

请注意, std::stoi(x)可能不够好。 它不会解析整个字符串,只是解析到有效int的末尾。 最后可能会有垃圾被忽略。 与其忽略垃圾,不如拒绝输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM