String



int main()

{

char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };



cout << "Student Names";

cout << "\nStudent 1: " << StudentName[0];

cout << "\nStudent 2: " << StudentName[1];

cout << "\nStudent 3: " << StudentName[2];

cout << "\nStudent 4: " << StudentName[3];



return 0;

}


this code work fine...but i want to take name from user..how i store it in character array through getline()..
please explain me..
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main()
{
    char ar[20];
    std::cin.getline(ar, 20);

    std::cout << ar << std::endl;

    return 0;
}


I suggest you read about std::string, which is a more convenient and C++ style I think.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <type_traits>

int main()
{
	char StudentName[4][10];

	for ( size_t i = 0; i < std::extent<decltype( StudentName )>::value; i++ )
	{
		std::cout << "Enter name of student " << i + 1 << ": ";
		std::cin.getline( StudentName[i], sizeof( StudentName[i] ) );
	}

	for ( size_t i = 0; i < std::extent<decltype( StudentName )>::value; i++ )
	{
		std::cout << StudentName[i] << std::endl;
	}
	std::cout << std::endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <iostream>
#include <cstring> // i don't think it's needed but i used it because of some compilers
using namespace std;

int main() {
	string student_name[4];
	for( int i = 0; i < 4; ++i )
		cin >> student_name[i];
	for( int i = 0; i < 4; ++i )
		cout << student_name[i] << endl;
	return 0;
}



@mokhi64

#include <iostream>
#include <cstring> // i don't think it's needed but i used it because of some compilers


I do not know what compilers you are speaking about but instead of

#include <cstring>

you must write

#include <string>
Last edited on
@ vlad
no different ! I promise.
but it's better to know some header files like <math.h>, <string.h> and etc, have a newer version with some small complitions .
so for being standard & update i suggest using <cstring> or <cmath>
Last edited on
I do not know what you are promising there.

cstring does not contain the definition of C++ class std::string that you are using in your example. It contains standard C functions placed in the global namespace. That is it has nothing common with std;:string. That to use std::string you have to include header string without any prefix 'c'. By the way this prefix in C++ headers means that this header corresponds to some standard C header.
Topic archived. No new replies allowed.