Concatenare doua numere short intr-un intreg

Intrebari despre limbajul C++, standardul C++, STL, OOP in C++ sau alte subiecte nelegate de VisualC++
Post Reply
Lady_In_Red
Junior
Junior
Posts: 5
Joined: 10 Jan 2015, 16:49
Judet: Timiş

Concatenare doua numere short intr-un intreg

Post by Lady_In_Red » 07 Feb 2015, 23:36

Salutare.

Am o problema in care se cere sa se concateneze oua numere short intr-un numar intreg.
Problema apare in momentul in care introduc cele doua numere short.
Nu stiu de ce, dupa ce introduc al doilea numar, ceva imi suprascrie primul numar avand valoarea zero.

Codul meu :
#include <stdio.h>
#include <stdlib.h>

int main()
{
short var_1, var_2;
int Combined_Data;
printf("\n Enter first number : ");
scanf("%i", &var_1);
printf("\n Enter the second number : ");
scanf("%i", &var_2);
Combined_Data = (((int)var_1) << 16) | var_2;
printf("\n The concatenated variable : %d\n", Combined_Data);
return 0;
}
Attachments
Untitled.png
Untitled.png (65.23 KiB) Viewed 3108 times



User avatar
zlatomir
Membru++
Membru++
Posts: 282
Joined: 04 Jul 2009, 23:59
Location: Arad
Contact:

Re: Concatenare doua numere short intr-un intreg

Post by zlatomir » 08 Feb 2015, 01:18

Ai o corupere de stack la scanf, i-ul scrie 4 bytes (un int), e ca si d, doar ca nu e in baza 10, un numar care incepe cu 0 va fi in baza 8 sau 0x pt baza 16, tu ai nevoie de hd pt a citi un short:

Code: Select all

scanf("%hd", &var_1);//la fel si pt var_2
cppreference

Post Reply