-1

I am building a program for a student percentage generator. In the program, I want to print the entered name of the student upto specific characters, say 5. I am using an array string. I have searched alot but could not find a proper answer to the problem.

I have tried using only arrays. [I am a beginner]

#include<iostream>

using namespace std;
int main()
{
  cout<<"Enter your name:";
  char name[20]; 
  cin>>name; //want to show only first 5 name letters
  cout<<"Your name is "<<name;

  return 0;
}

I want it to collect the data entered by user and print the entered data upto 5 characters. Is there any way to do it?

yoismak
  • 45
  • 2
  • 9

3 Answers3

5

Yup, you could use substr method provided by the string data type.

#include<iostream>

using namespace std;
int main()
{
  string name; 
  cout << "Enter your name:";
  cin >> name; 
  cout << "Your name is " << name.substr(0, 5);

  return 0;
}
Danyal Imran
  • 2,515
  • 13
  • 21
  • 3
    Please, don't teach new users some of bad practices from the get-go: [Why is “using namespace std” considered bad practice](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Algirdas Preidžius Jan 26 '19 at 10:44
  • What if the name is Max or Tim, that is shorter than 5 characters? Will the program crash? Since this is C++ I assume the answer is yes. – Roland Illig Jan 26 '19 at 10:45
  • @RolandIllig It won't, it will work fine for length < 5 as well. – Danyal Imran Jan 26 '19 at 10:46
  • The output is also missing the final newline. And no, std::endl is not appropriate here, just use a simple `"\n"` for this. – Roland Illig Jan 26 '19 at 10:47
  • @AlgirdasPreidžius I am not a C++ expert or average, I just know some basics back from my university days. – Danyal Imran Jan 26 '19 at 10:47
  • 2
    @RolandIllig Don't assume. Read documentation: [std::string::substr](https://en.cppreference.com/w/cpp/string/basic_string/substr). "Returns a substring [pos, pos+count). **If the requested substring extends past the end of the string, or if count == npos, the returned substring is [pos, `size()`).**" (emphasis mine) – Algirdas Preidžius Jan 26 '19 at 10:47
0

Quite simple:

std::cout.write(name, std::min(5, strlen(name));

Or, if you use a std::string (it would be preferrable for input reading to avoid buffer overflow):

std::cout.write(name.c_str(), std::min(5, name.length()); // or .data()
Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0

If you don't want to store the entire name and only just 5 characters,

#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

int main()
{
    char name[6];
    for(int i = 0; i < 3; i++) {
        // Only read first 5 characters
        cin >> setw(sizeof name) >> name;
        // ignore rest of input buffer
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
        cout << name << endl;
    }
    return 0;
}
HariUserX
  • 1,341
  • 1
  • 9
  • 17