如何从特定索引的字符串中提取int?
我目前正在从事作业。我需要拿起字符串的地方,在索引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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的代码中,使用了
&lt;&lt;
操作符int
的过载。这将值打印为积分数字,而不是打印字符。如果要打印字符,只需将
readval
的类型更改为char
如果要使用
int
,则可以使用十进制数字的字符在ASCII表中以升序顺序“彼此相邻”的事实。In your code the overload of the
<<
operator takingint
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
tochar
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.