Cpp cin to array

How to use cin for an array in C++ [SOLVED]

In c++ cin array is not performed in one cin statement. In this article we will learn about array input in c++. To understand array input, we first need to understand what an array is and how does it work.

Understanding Arrays

Arrays are used to store multiple values, rather than storing similar data in separate variables, which is tedious as well as memory consuming, we create an array, which is a container that contains multiple values. Written below is a code that is the record of 5 students marks in separate variables and then in an array.

#include using namespace std; int main()
marks of student1: 1 marks of student2: 2 marks of student3: 3 marks of student4: 4 marks of student5: 5

Now, the code written below is the same but data is stored in an array

#include using namespace std; int main() < int student[5] = ; cout

The output of the following code is :

the marks of student 1 are : 1 the marks of student 2 are : 2 the marks of student 3 are : 3 the marks of student 4 are : 4 the marks of student 5 are : 5

Cin Array

If you want input from the user you need to cin array, but cin cannot be directly used in this case, it will show an error like the one given below

#include using namespace std; int main() < int student[5] = ; cin >> student; >
cinarray.cpp:6:12: error: invalid conversion from ‘int*’ to ‘long int’ [-fpermissive] 6 | cin >> student; | ^~~~~~~ | | | int* cinarray.cpp:6:12: error: cannot bind rvalue ‘(long int)((int*)(& student))’ to ‘long int&’

So we use a for loop for the input of the array, the loop will run till the size of the array, and take input of array at every index, this is how cin array is executed in C++.

Читайте также:  Python управление шаговым двигателем

The code for cin array is written below :

#include using namespace std; int main() < int student[5] = ; //cin array for (int i = 0; i < 5; i++) < cout > student[i]; > //output cout

The output of code of cin array is :

enter student marks 1 enter student marks 2 enter student marks 3 enter student marks 4 enter student marks 5 the marks of student 1 are : 1 the marks of student 2 are : 2 the marks of student 3 are : 3 the marks of student 4 are : 4 the marks of student 5 are : 5

Conclusion

In this article we studied what are arrays, how do we store elements in arrays and how cin arrays take place. It is executed in a loop unlike other variables.

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Cpp cin to array

I am trying to put values from cin that is put in before a loop, into an array. However, when I output the array, the values are not stored in. (Actually garbage). What do you think?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main () < const int MAX_WEIGHT = 20; const int CARS = 5; int train_cars[CARS], num_boxes, num_loaded, total; cout "How many boxes of freight should each car be loaded with?" > num_boxes; for(int i = 0; i < CARS; i++) < num_boxes >> train_cars[i]; cout

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 int main () < const int MAX_WEIGHT = 20; const int CARS = 5; int train_cars[CARS], num_boxes, num_loaded, total; std::cout "How many boxes of freight should each car be loaded with?" > num_boxes; for(int i = 0; i < CARS; i++) < train_cars[i] = num_boxes; std::cout >

Just for my understanding, in my head, the logic is: num_boxes "goes into" (or >>) the array of train_cars[i].

>> is the stream extraction operator. This means that a stream of data, say from the keyboard is extracted and stored as a variable. Yours was an interesting (mis) interpretation but your num_boxes is an integer stored in memory, not a stream of data. You didn't have to 'stream' num_boxes over to train_cars[i], you just make them equal with the = operator. Hope this helps. 🙂

It absolutely does. However, on the same topic, why would something like this work:

const int NUM_EMPLOYEES = 10 int employee[NUM_EMPLOYEES]; for(int i = 0; i < NUM_EMPLOYEES; i++) < cout "Employee #" << (i+1) ": " cin >> employee[i]; cout " has been added to the list" 

Where as the user is inputing the data directly into the array. VS. my code at the top where the user is inputting the data(just a single data in my code) into a variable, and then the variable is putting it into the array sub count?

It seems like the same thing to me, just with an added step.

Thanks again for the input.

every line in your example is moving data from or to a stream. so << >> work.

your original problem (line14) involved no streams. so no use of >

Im still getting garbage when I cout the array. My code now looks like this:

const int CARS = 5; int train_cars[CARS]; for(int i = 0; i < CARS; i++) < cin >> train_cars[i]; for (int i = 0; i < CARS; i++) < cout > 

So , lets say that I cin an integer of 5, it SHOULD store 5 into each array, and then once it ends the loop, it goes to the next loop(which is inside the first loop) and displays the array sub i.

The output Im getting is:
5
4285968
2686656
2686712
2686924

 int main () < const int NUM_CARS = 5; // NUM_CARS is a slightly better name int train_cars[NUM_CARS] = ; // initialise to all zeroes // first read in the values into the array for( int i = 0; i < NUM_CARS; ++i ) std::cin >> train_cars[i]; // after all the values have been read, print them out for( int i = 0; i < NUM_CARS; ++i ) std::cout ' ' ; std::cout '\n' ; >

So what I was doing wrong was not initializing the array to zero? How is that any different from not initializing?

Each element would contain the value of 0, where as if not initialized, each value would contain garbage value for the empty space.

In both of these circumstances, the value that is in the array is being overwritten by the input of cin. How is it different?

The confusion comes because Ive never initialized an array to anything before.

However, when I do use the code youve provided, and cout it (using 5 as a int that is put in from the user) , the values are:
5
0
0
0
0

partly, that is why you got garbage, now you get zeroes.

you are printing out the entire array after entering only the first value.

const int CARS = 5; int train_cars[CARS]; for(int i = 0; i < CARS; i++) < cin >> train_cars[i]; // enter a value into the array for (int i = 0; i < CARS; i++) // print the entire array! < cout >

unnest your loops like JLBorges shows.

Ah, now that works. Thank you.

So to the original problem, Getting that input from the user into a variable BEFORE then loop, and then using that variable for the loop. What is the correct syntax for that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const int CARS = 5; int train_cars[CARS] = , num_boxes, num_loaded, total, temp; cout "How many boxes of freight should each car be loaded with?" > num_boxes; for(int i = 0; i < CARS; i++) < num_boxes = train_cars[i]; >cout "Test" for (int i = 0; i

Источник

Cpp cin to array

I am trying to put values from cin that is put in before a loop, into an array. However, when I output the array, the values are not stored in. (Actually garbage). What do you think?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main () < const int MAX_WEIGHT = 20; const int CARS = 5; int train_cars[CARS], num_boxes, num_loaded, total; cout "How many boxes of freight should each car be loaded with?" > num_boxes; for(int i = 0; i < CARS; i++) < num_boxes >> train_cars[i]; cout

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 int main () < const int MAX_WEIGHT = 20; const int CARS = 5; int train_cars[CARS], num_boxes, num_loaded, total; std::cout "How many boxes of freight should each car be loaded with?" > num_boxes; for(int i = 0; i < CARS; i++) < train_cars[i] = num_boxes; std::cout >

Just for my understanding, in my head, the logic is: num_boxes "goes into" (or >>) the array of train_cars[i].

>> is the stream extraction operator. This means that a stream of data, say from the keyboard is extracted and stored as a variable. Yours was an interesting (mis) interpretation but your num_boxes is an integer stored in memory, not a stream of data. You didn't have to 'stream' num_boxes over to train_cars[i], you just make them equal with the = operator. Hope this helps. 🙂

It absolutely does. However, on the same topic, why would something like this work:

const int NUM_EMPLOYEES = 10 int employee[NUM_EMPLOYEES]; for(int i = 0; i < NUM_EMPLOYEES; i++) < cout "Employee #" << (i+1) ": " cin >> employee[i]; cout " has been added to the list" 

Where as the user is inputing the data directly into the array. VS. my code at the top where the user is inputting the data(just a single data in my code) into a variable, and then the variable is putting it into the array sub count?

It seems like the same thing to me, just with an added step.

Thanks again for the input.

every line in your example is moving data from or to a stream. so << >> work.

your original problem (line14) involved no streams. so no use of >

Im still getting garbage when I cout the array. My code now looks like this:

const int CARS = 5; int train_cars[CARS]; for(int i = 0; i < CARS; i++) < cin >> train_cars[i]; for (int i = 0; i < CARS; i++) < cout > 

So , lets say that I cin an integer of 5, it SHOULD store 5 into each array, and then once it ends the loop, it goes to the next loop(which is inside the first loop) and displays the array sub i.

The output Im getting is:
5
4285968
2686656
2686712
2686924

 int main () < const int NUM_CARS = 5; // NUM_CARS is a slightly better name int train_cars[NUM_CARS] = ; // initialise to all zeroes // first read in the values into the array for( int i = 0; i < NUM_CARS; ++i ) std::cin >> train_cars[i]; // after all the values have been read, print them out for( int i = 0; i < NUM_CARS; ++i ) std::cout ' ' ; std::cout '\n' ; >

So what I was doing wrong was not initializing the array to zero? How is that any different from not initializing?

Each element would contain the value of 0, where as if not initialized, each value would contain garbage value for the empty space.

In both of these circumstances, the value that is in the array is being overwritten by the input of cin. How is it different?

The confusion comes because Ive never initialized an array to anything before.

However, when I do use the code youve provided, and cout it (using 5 as a int that is put in from the user) , the values are:
5
0
0
0
0

partly, that is why you got garbage, now you get zeroes.

you are printing out the entire array after entering only the first value.

const int CARS = 5; int train_cars[CARS]; for(int i = 0; i < CARS; i++) < cin >> train_cars[i]; // enter a value into the array for (int i = 0; i < CARS; i++) // print the entire array! < cout >

unnest your loops like JLBorges shows.

Ah, now that works. Thank you.

So to the original problem, Getting that input from the user into a variable BEFORE then loop, and then using that variable for the loop. What is the correct syntax for that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const int CARS = 5; int train_cars[CARS] = , num_boxes, num_loaded, total, temp; cout "How many boxes of freight should each car be loaded with?" > num_boxes; for(int i = 0; i < CARS; i++) < num_boxes = train_cars[i]; >cout "Test" for (int i = 0; i

Источник

Заполнить массив цифрами числа, считанного через cin

Здрасти, как ввести в массив int mMass[5] число 12345 с помощью cin>>? Нужно чтобы в mMass[0] записалась 1, в mMass[1] записалась 2 . и тд.

Заполнить массив цифрами заданного числа, расположенными в обратном порядке
Дано натуральное число n (n<10^6). Заполнить массив его цифрами, расположенными в обратном порядке.

Заполнить массив цифрами заданного числа, расположенными в обратном порядке
Дано натуральное число n ≤ 999999. Заполнить массив его цифрами, расположенными в обратном порядке.

заполнить массив 6*6 цифрами от 1 до 21 по следущей схеме.
заполнить массив 6*6 цифрами от 1 до 21 по следущей схеме! 6 0 0 0 0 0 5 11 0 0 0 0 4.

Заполнить массив из пяти значений цифрами
1. Заполнить массив из пяти значений цифрами (при объявлении): первое - 123 второе - 94 третье -.

int* mas = (int*)malloc(10*sizeof(int)); for(int i = 0; i  10; i++) cin>>mas[i]; // . delete [] mas;
#include using namespace std; int main() { int mas[5]; for (size_t i = 0 ; i  5 ; i++) mas[i]=i+1; for (size_t i = 0 ; i  5 ; i++) cout[i]; return 0; }

Источник

Как записать в массив чар через cin текст с пробелами "Здравствуй, как дела?", что бы потом определить его длину

Как через Query в Delphi записать в таблицу текст c такими кавычками " "(двойными)?
Как через Query в Delphi записать в таблицу текст c такими кавычками " "(двойными)? Мне нужно в.

Лучший ответ

Сообщение было отмечено DarkShaddow как решение

Решение

char s[256]; cout  "String:\n"; cin.getline(s, 256);

Создать текстовый файл и записать в него фразу "Здравствуй, мир!"
Создать текстовый файл и записать в него фразу "Здравствуй, мир!"

Как заполнить массив буквами "через одну", начиная с "а"
Буквами "через одну",начиная с "а":то есть массив заполняется буквами 'a','c','e' и тд. Размер.

Как выделить нужное слово из "чар" перемнной
Если пользователь наберет к примеру "open file.txt",то как сделать так чтобы программа распознала.

Источник

Оцените статью