简体   繁体   中英

Why can't my integers be transferred to an array?

I want to make a program that works with integers that were inputted using space and not enter. when you input the integers 12 80 33 99 with space between each one of them, then the code will separate the integers and put them into an array.

I'm using codeblocks, C++

int main(){
int A;
int j [10] ={0,0,0,0,0,0,0,0,0,0};
cin >> A;
string As;
bool code = true;
int hasil [A][10];
getline(cin,As);
    for (int i = 0 ; i < A ; i++){

        while (code){

            if( cin.get() != '\n'){

            cin >> hasil[i][j[i]];
            j[i]++;

            }else{ code = false;}
    }}
    for (int i = 0 ;i < A ; i++){
        for (int x = 0; x != j[i]; x++){
            cout << hasil[i][x]<< " " ;
        }
        cout << " " << endl;
    }
return 0;}

When I input 25 17 70 88 , I expected the output to be 25 17 70 88 too, but the actual output was 5 17 70 88 . Where is my first 2 ?

您的2cin.get()的调用吃掉了,该文件读取一个字符,然后您的代码将其丢弃。

I can't understand exactly what you are trying to do but i can see an error in your code which might cause undefined behaviour. int hasil[A][10] is a static array which means compiler must know its size at compile time, however A is not a compile time constant. If you don't know the size of your array you should use a pointer instead or even better a std container such as std::vector . To make your code more readable you can also delete the code variable and replace your first for loop body with

while(cin.get() != '\n)
{
   cin >> .....
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM