vendredi 16 avril 2021

C++ Getting Garbage Values while taking input [duplicate]

I am getting garbage values while taking input in C++.

I'm taking Input and storing it in matrix using vector. If there are other way you can suggest me that too, but how can I solve this?

#include <iostream>

using namespace std;

#include <sstream>
#include <vector>


int main(){
    // Taking input X,Y
    int x,y;
    cin >> x;
    cin >> y;

    // Printing x,y
    cout << x << endl;
    cout << y << endl;

    // Empty matrix
    int matrix[x][y];

    for(int i=0; i<x; i++){
        // Getting Line for storing values in matrix
        
        // Creating Temp Vector
        vector<int> v;
    
        int p;
        string s;
        
        // Take string as input
        getline(cin, s);
        
        // Convert to String Stream
        istringstream T(s);
        
        // Pushing each element to vector
        while(T >> p){
            v.push_back(p);
        }
        
        // storing in matrix
        for(int j=0; j<v.size(); j++){
            matrix[i][j] = v.at(j);
        }
    }
    
    // Displaying Matrix
    for(int i=0; i<x; i++){
        for(int j=0; j<y; j++){
            cout << matrix[i][j] << " ";
        }
        cout << "\n";
    }
    
}

Input are in this format

4
4
0 1 1 0 
1 1 1 1 
1 1 1 1
1 1 0 0

Getting Ans :-

4
4
1387623040 32765 4198272 0 
0 1 1 0 
1 1 1 1 
1 1 1 1 

Aucun commentaire:

Enregistrer un commentaire