如何从特定索引的字符串中提取int?

发布于 2025-01-23 09:49:38 字数 366 浏览 1 评论 0原文

我目前正在从事作业。我需要拿起字符串的地方,在索引1上读取值,然后使用该值将值分配给整数。

    int main()  
{
   string num;
   cin>> num;
   int readval;
   readval= num.at(0);
   cout << readval;
}

问题是,每当我打印ReadVal时,它的数字从未在我指定的索引位置。例如,如果我想从类似4 1 2 3 4的字符串中num.at(0)= 4。我希望readval等于该数字(在这种情况下为4),但是当我打印readval时,它会打印52而不是什么值在索引中。我知道52是4的ASCII代码,但我不知道为什么它对我不起作用

I'm currently working on an assignment. Where I need to take a string, read the value at index 1 and use that value to assign a value to an integer.

    int main()  
{
   string num;
   cin>> num;
   int readval;
   readval= num.at(0);
   cout << readval;
}

the problem is whenever I print readval its never the number at the index location that i specified. for example if I wanted num.at(0)= 4 from a string like 4 1 2 3 4. I want readval to be equal to that number (in this case 4) but when I print readval it prints 52 instead of what the value is in the index. I know that 52 is the ASCII code for 4 but I don't know why its not working for me

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠檬色的秋千 2025-01-30 09:49:39
#include <bits/stdc++.h>
using namespace std;
int main()  
{
   string num;
   cin>> num;
   int readval;
   readval= num.at(0);
   cout << readval - 48;
}
#include <bits/stdc++.h>
using namespace std;
int main()  
{
   string num;
   cin>> num;
   int readval;
   readval= num.at(0);
   cout << readval - 48;
}
各空 2025-01-30 09:49:38

在您的代码中,使用了&lt;&lt;操作符int的过载。这将值打印为积分数字,而不是打印字符。

如果要打印字符,只需将readval的类型更改为char

char readval = num.at(0);
cout << readval;

如果要使用int,则可以使用十进制数字的字符在ASCII表中以升序顺序“彼此相邻”的事实。

int readval = num.at(0) - '0';
cout << readval;

In your code the overload of the << operator taking int is used. This prints the value as an integral number instead of printing the character.

If you want to print the character, just change the type of readval to char

char readval = num.at(0);
cout << readval;

If you want to work with an int, you can use the fact that the chars for the decimal digits are "next to each other" in the ascii table in ascending order.

int readval = num.at(0) - '0';
cout << readval;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文