我的函数返回一个错误的值
My function rerurns a wrong value c++
#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)
是字符串hh
中zeichen
位置的字符。类型为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'由与数字相邻且顺序相同的字符代码表示。
- 试图修复一个错误,该错误不会让我开始编程其余部分
- MSVC 无法根据模板参数进行数学运算,这是一个错误吗?
- 我正在尝试一个傻瓜 C++ 练习,我遇到了一个错误,说类 'GraduateStudent' 没有任何名为 'advisor' 的字段
- 零四元数和任何向量都不为零的特征积,这是一个错误吗?
- 处理程序的模块列表中有一个错误的模块"WebSocketModule"
- 在 C++ 中使用 "transform" 会给出一个错误,指出这未在作用域中声明
- 在Cython中使用C库时,我遇到了一个错误
- 我需要帮助创建一个评分系统,但它一直给我一个错误,注释掉的整数是给我带来麻烦的部分
- 我试图用c++编写递归fibonacci序列,但当我编译时,我遇到了一个错误
- 从system()调用G++会返回一个错误
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 我收到一个错误无效的操作数,类型为 const char [42] 和二进制"运算符+"的双倍数
- 使用声明:GCC 和 Clang 的另一个错误?
- 全球免费给出一个错误.调试器不解释
- 相对于继承的构造函数,gcc 编译器是否还有一个错误?
- 为什么直接传递"this"指针来存档是一个错误,而另一个相同类型的指针是可以的?
- 为什么第三板有一个错误
- 如何编写一个错误结构,该结构可以包含不同的强键枚举作为错误代码
- 使用本地类型声明的G lambda被使用但从未定义 - 确实是一个错误
- 我需要在 Android Studio 中构建 NDK. 但它返回一个错误