我的函数返回一个错误的值

My function rerurns a wrong value c++

本文关键字:一个 错误 函数 返回 我的      更新时间:2023-10-16
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>

using namespace std;
int StrInt(int x,string y)
{
    return y.at(x);
    cout << y.at(x) << "hallo";
}
int Get_Int(int linie, int zeichen){
    ifstream file;
        string line;
        vector<string>lines;
        file.open("C:/Soi/input/input.txt");
        if(file.is_open())
        {
            cout << "file is open" << endl;
            int x = 0;
            lines.resize(1);
            while(getline(file, line))
            {
                lines[x] = line;
                lines.push_back(line);
                x++;
                cout << lines[x] ;
            }
            lines.erase (lines.begin()+x);
            cout << endl;
        }
        else{
            cerr<<"file could not be opened!";
        }
        for(unsigned int i = 0; i < lines.size(); i++)
        {
                cout << lines[i] << "   /" << i << endl;
        }
        string hh = lines[linie];
        cout << hh.at(zeichen) << " hallo" << endl;
        cout << "returned value: " << hh.at(zeichen) << endl;
        return hh.at(zeichen);
}

int main() {
    cout << "Programm gestartet" << endl;
    int zeichen = 0;
    int linie = 0;
    int resultat = Get_Int(linie, zeichen);
    int opperand1 = 2;
    int opperand2 = 48;

    if (opperand1 + opperand2 == resultat){
        cout << resultat << endl << "true" ;
        return 0;
    }
    else{
        cout << resultat << endl;
        return 0;
    }
    return 0;
}

我想要得到的正常值是:3代码还没有完成。后来我试图打印出来,如果这两个值是类似的结果。我试着在代码中做一些改变,但它不起作用。我从

得到的值

cout & lt; & lt;hh.at (zeichen)

与我从

得到的值不同。

cout & lt; & lt;结果

Thank you very much

对不起,我的英语不好。

你的函数被声明为返回一个int,但是你返回的是:

    string hh = lines[linie];
    /*...*/
    return hh.at(zeichen);

问题是string::at返回一个char&char s愉快地转换为int没有问题,但你不会得到你期望的结果。您必须解析该数字,例如:

    return hh.at(zeichen) - '0';

hh.at(zeichen)是字符串hhzeichen位置的字符。类型为char &

当您使用cout << hh.at(zeichen)打印该字符时,它将打印该字符,例如'0'。

int Get_Int(int linie, int zeichen) {
    ...
    return hh.at(zeichen);
}
int result = Get_Int(linie, zeichen);

在这个函数中,您返回字符,但编译器需要将其转换为int。现在重要的是char是如何存储的,它有什么值。char只包含(通常)一个字节长度的数字。如何解释这些取决于系统。对于当前的pc,字符通常以ASCII格式存储。"0"的ASCII码为48。

当您打印char时,那么您将得到具有相同ASCII码(代码48,字符'0')的字符。如果像result一样打印int,则会打印出数字(首先转换为字符串,然后打印;数字48,字符串"48")。

您可以打印(char)result,这将把int转换回char, cout将作为字符打印。或者您可以将char转换为char中的字符所表示的数字。在ASCII编码的情况下,如果你确定所有字符都表示数字,你可以减去hh.at(zeichen) - '0',它给你0为'0',1为'1'等等。但是您应该记住,这只适用于ASCII和EBCDIC这样的字符表示,其中'0'到'9'由与数字相邻且顺序相同的字符代码表示。

相关文章: