In: Computer Science
I am attempting to construct a queue through a linked list using a node data structure with different data types (char, int) in C++. Is this possible or can the queue be of only one data type? My queue has both names and numbers in it so what data type would be best? Can a "char" data type store integers? Can a "string" data type store integers?
If you want to construct a queue through a linked list using a node data structure with same data types (all the data types are charr or all the data types are int) then you should use template concept, But if you want to construct a queue data structure with different data types in the same queue, then you should use string type.
Yes it is possible if you use string type. Just remember, when you store other data type rather than string, then it is required to convert from other type to string, and when you read the data then also it is required to convert from string to other type.
If you use string type then you can store names as well as numbers, it is a best idea.
"char" data type can store limited integer value, only from -128 to +127. So if you store large number then you will lost the data. Therefore, do not try to store integer value to a char variable, except very low range integer value.
"string" data type can store other data including integer, but it may need some conversation.
Suppose, you want to read some integer value:
Example 1:
string s;
cout<<"Enter a number:";
cin>>s; //here if you enter an integer value then e.g 123 then 123 value will be into string variable s without conversation.
cout<<s; //print 123
Example 2:
int n;
cout<<"Enter a number:";
cin>>n; //here if you enter an integer value then e.g 123
string s = n; //illegal statement
string s = to_string(n); //you can use this statement or you can also use itoa() function for conversation
cout<<s; //print 123
Example 3:
string s = "123";
int n = s; //illegal statement
int n = stoi(s); //you can use this statement or you can also use atoi() function for conversation