在 C++ 中将多个数字读入单个有符号字符 [英] Reading multiple digits into a single signed char in C++

查看:99
本文介绍了在 C++ 中将多个数字读入单个有符号字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在为一个简单的 codeforces 回合构建一个愚蠢的应用程序,并决定我想用我的晚上过度优化.

所以我有以下代码,其中字符串signed char"的每个实例最初都是short",现在我遇到的问题是我想使用cin,逐个数字和作为读取输入一旦我使用有符号的 char 数据类型,cin 现在一次读取一个字符.

例如,如果输入是 (4\n33 44 11 22),cin 现在会将 number_of_men 设置为 (4),将 tmp 设置为 4 then 3 then 3 then 4,而不是 33 then 44 then 11 then 22.

如何让 cin 将多个文本字符作为数字读入单个有符号字符变量中?

#include 使用命名空间标准;int主(){ios::sync_with_stdio(false);签名字符 number_of_men;cin >>number_of_men;签名字符tmp;有符号字符最大值 =0;有符号字符 max_loc=0;有符号字符最小值 = 101;签名 char min_loc=0;for (signed char i=0; i  max){max_loc = i;最大值 = tmp;}如果(tmp <= min){min_loc = i;分钟 = tmp;}}cout<<max_loc + number_of_men-1 -min_loc-(max_loc > min_loc)<<结束;返回0;}

解决方案

你想要 int8_t 来自 .

cin 根据变量类型确定正确的读操作.char 变量意味着您获得第一个字符.int 变量意味着您获得第一个数字.

So I was building a silly application for an easy codeforces round and decided i wanted to spend my evening over-optimizing.

So I had the following code, where every instance of the string "signed char" was originally a "short", now the problem I am encountering is that I want to read an input using cin, number by number, and as soon as I drop to the signed char data type, cin now reads a single character at a time.

For example if the input is (4\n33 44 11 22), cin will now set number_of_men to (4) and tmp to 4 then 3 then 3 then 4 as opposed to 33 then 44 then 11 then 22.

How do I get cin to read multiple characters of text as a number into a SINGLE signed char variable?

#include <iostream>
using namespace std;

int main ()
{
ios::sync_with_stdio(false);
signed char number_of_men;

cin >> number_of_men;
signed char tmp;
signed char max =0;
signed char  max_loc=0;
signed char min = 101;
signed char min_loc=0;

for (signed char i=0; i < number_of_men; i++) {
    cin >> tmp; 
    if(tmp > max)
    {
        max_loc = i;
        max = tmp;
    }
    if(tmp <= min)
    {
        min_loc = i;
        min = tmp;
    }
}
    cout << max_loc + number_of_men-1 -min_loc-(max_loc > min_loc)<< endl;
    return 0;
}

解决方案

You want int8_t from <stdint.h>.

cin determines the correct read operation based on the variable type. A char variable means you get the first character. An int variable means you get the first number.

这篇关于在 C++ 中将多个数字读入单个有符号字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆