【问题标题】:How would you pass a string to a function and return an integer?如何将字符串传递给函数并返回整数?
【发布时间】:2017-10-24 08:35:28
【问题描述】:

我发现我需要开始使用 getline(cin, input);对于我的用户输入。我想出了如何使用 stringstream 将来自用户的字符串转换为 int,以便我可以在数学函数中存储和使用数字。

例如,假设您需要向用户询问学生 ID,您可以轻松地将其存储为字符串,因为您很少需要使用它来做任何类型的数学方程式。但是,如果你要问成绩,你需要平均下来并转换为 GPA,那就是另一回事了。

我基本上想要求用户通过 getline 输入一个数字,然后将输入转换为一个 int,但作为一个函数,这样我就不需要在每次需要转换的时候都输入相同的交易。

例子:

#include<iostream>
#include<conio.h>
#include<string>
#include<sstream>

using namespace std;

class students{

    int s1, s2, s3;
    string name, id, input;

public:
    void getData(){
            cout << "Enter ID: ";
            getline(cin, id);

            cout << "Enter Name: ";
            getline(cin, name);

            while(true){
                cout << "Enter grades for Math: ";
                getline(cin, input);

                stringstream convert(input);
                if(convert >> s1)
                    break;
                cout << "Invalid Grade; Please Try Again! " << endl;
            }
            while(true){
                cout << "Enter grades for Science: ";
                getline(cin, input);

                stringstream convert(input);
                if(convert >> s2)
                    break;
                cout << "Invalid Grade; Please Try Again! " << endl;
            }
            while(true){
                cout << "Enter grades for English: ";
                getline(cin, input);

                stringstream convert(input);
                if(convert >> s3)
                    break;
                cout << "Invalid Grade; Please Try Again! " << endl;
            }
    }

    void showData(){
        cout << "\n" << id << "\t" << name << "\tMath: " << s1 << "\tScience: " << s2 << "\tEnglish: " << s3;
    }
};

int main(){
    students s[20];
    int i, numOfStudents;
    string input;

    while(true){
        cout << "\nNumber of Students? ";
        getline(cin, input);

        stringstream convert(input);
        if(convert >> numOfStudents)
            break;
        cout << "Invalid Grade; Please Try Again! " << endl;
    }

    for(i = 0; i < numOfStudents; i++){
        s[i].getData();
    }

    for(i = 0; i < numOfStudents; i++){
        s[i].showData();
    }

    _getch(); //Only there to keep the command line window open.
    return 0;
}

【问题讨论】:

  • 不知道你在问什么 - 它是一个函数的签名,它接受一个 int 并返回一个字符串?
  • 有几种方法可以做到这一点。 std::istringstreamstd::stoi()

标签: c++ string int stringstream


【解决方案1】:

你需要一个函数。比如:

int getGrade(const std::string& subject)
{
   while(true){
        std::cout << "Enter grades for " << subject << ": " << std::flush;
        std::string input;
        std::getline(std::cin, input);

        std::stringstream convert(input);
        int result;
        if(convert >> result)
             return result;
        std::cout << "Invalid Grade; Please Try Again! " << std::endl;
    }
}

用法类似于:

s1 = getGrade("Math");

【讨论】:

  • 我明白了!将主题作为字符串传递完全让我无法理解。非常感谢!我只是在为自己的时间练习,所以这只是我为自己做的一个小项目,以改进我的编码。
  • 在这种情况下,您实际上可以将其作为 const char * 传递 - 我只是倾向于默认为 std::string,除非另有充分理由。
【解决方案2】:

您可以通过引用 const 来传递字符串并利用 std::stoi 函数:

int getGrade(const std::string& s) {
    try {
        int result = std::stoi(s);
        return result;
    }
    catch (std::invalid_argument) {
        std::cout << "Could not convert to integer.";
        return -1;
    }
}

并像下面这样使用它:

int main() {
    int x;
    std::string s1;
    std::cout << "Enter grade: ";
    std::getline(std::cin, s1)        
    x = getGrade(s1);
}

【讨论】:

    【解决方案3】:

    您要做的是将复制的代码提取到它自己的函数中,如下所示:

    ...
    
    int readGrade(const char* subject) {
        while(true) {
            cout << "Enter grade for " << subject << ": ";
            string input;
            getline(cin, input);
    
            stringstream convert(input);
            int n;
            if(convert >> n)
                return n;
            cout << "Invalid grade, please try again." << endl;
        }
    }
    
    class students{
    
        int s1, s2, s3;
        string name, id, input;
    
    public:
        void getData(){
            cout << "Enter ID: ";
            getline(cin, id);
    
            cout << "Enter Name: ";
            getline(cin, name);
    
            s1 = readGrade("Math");
            s2 = readGrade("Science");
            s3 = readGrade("English");
        }
    
        void showData(){
            cout << "\n" << id << "\t" << name << "\tMath: " << s1 << "\tScience: " << s2 << "\tEnglish: " << s3;
        }
    };
    
    ...
    

    【讨论】:

      【解决方案4】:

      将您的循环之一提取到不同的函数并参数化您的“问题文本”:

      int get_input(const char* what)
      {
           while(true)
           {
               cout << what;
               string input;
               getline(cin, input);
      
               int temp;
               stringstream convert(input);
               if(convert >> temp) return temp;
      
               cout << "Invalid input; Please Try Again! " << endl;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-12
        • 2015-08-07
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        相关资源
        最近更新 更多