0

When I enter a value for the group_input variable, the program finishes, and I can't enter a value for the fio_input variable. If I enter a short value, I can proceed to enter a value for the fio_input variable. What's the problem?

#include <iostream>
using namespace std;

int main()
{
    unsigned char group_input, fio_input, result[7] = {0, 0, 0, 0, 0, 0, 0};

    cout << "\n    Enter your group name: ";
    cin >> group_input;
    cout << "\n    Enter your full name: ";
    cin >> fio_input;
}
  • 1
    What is wrong with using: `std::string` instead of fixed arrays? They are bound to give undefined behavior... C++ is extremely lenient when it comes to checking bounds and what you have here is simply *Undefined behavior*... – Ruks Feb 15 '19 at 07:59

3 Answers3

2

When you read into a char variable, the system will read characters. And a single char can only store a single character, so that's what will be read.

If you give a multi-character input then the first character will be stored in group_input, and the second in fio_input.

If you want to read strings (which seems to be what you want) then use std::string.

Using std::string is especially important if you want to avoid buffer overflows. C++ doesn't have bound-checking of arrays.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

You're asking for a name, which is an array of chars - a std::string.

#include <iostream>
#include <string>

int main(){
    std::string group_input, fio_input;

    std::cout << "\n    Enter your group name: ";
    std::cin >> group_input;
    std::cout << "\n    Enter your full name: ";
    std::cin >> fio_input;
}

You shouldn't use use namespace std; read here why.

Also if you want to input names with spaces use std::getline(std::cin, str); instead. Because if you std::cin "Roger Jones" to fio_input it will only save "Roger"

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
1

In this line

cin >> group_input;

you read from the standard input and write the result to an unsigned char variable. How many bytes will be read? This depends on the overloaded operator >> invoked by the above line. In your case, both "input lines" invoke an overload for the unsigned char, as this data type can only store one byte, it reads one byte. Hence, you can either input one-character names for both variables, or you change the data type of group_input and fio_input to something else, e.g. std::string. In this case, the operator >> overload is invoked that reads anything up to the next whitespace (but not including it) byte, where "whitespace byte" includes tab, newline etc.

lubgr
  • 37,368
  • 3
  • 66
  • 117