how to store character variable into two dimensional character variable - c++

I Want to store the value of user_uname and user_pwd to validuser[c][0] and validuser[c][1].Also string "normaluser" to validuser[c][2].
But it shows an error "cannot convert char * to char".This is my code:
char validuser[20][20];
int c;
char user_uname[20],user_pwd[20];
cout<<"\n Enter User Detail";
cout<<"\n enter Username:";
cin>>user_uname;
cout<<"\n Enter Password:";
cin>>user_pwd;
validuser[c][0] = user_uname;
validuser[c][1] = user_pwd;
validuser[c][2] = "normaluser";
c++;

Your validuser is an array of arrays or chars. You can only store single char in each spot, or you can use it as an array of "strings" (char arrays). If you definitely want to use C style strings, you should have a third dimension to do what you're trying, such as char validuser[20][3][20].
But since you are using C++, why not use std::vector<std::string> rather? And store usernames and passwords in a struct, not as consecutive strings. Using C++ strings and vectors will allow you to use any length of strings or any number of users without knowing the number beforehand or handling memory allocations yourself.

char validuser[20][20];
....
validuser[c][0] = user_uname;
The validuser[][] is a char so you are not OK to assign. In your code, you can use:
strncpy( &(validuser[c][0]), user_uname, 20 );
But why dont you use the std::vector or std::array? In most of the case, std::string provide good enough feature for you.

You must use string on this. Char only accept a single character, here is the modified code. Hope this helps :)
The First Dimension you only need 3 array because of the user name, password, and type. for the 2nd Dimension you can add as many as you want, I made it 3 so that it would accept 3 users.
#include<iostream>
#include<string>
using namespace std;
void main()
{
int pause;
string validuser[3][3];
int c = 0;
do
{
string user_uname, user_pwd;
cout << "\nEnter User Detail";
cout << "\nenter Username:";
cin >> user_uname;
cout << "Enter Password:";
cin >> user_pwd;
cout << endl;
validuser[c][0] = user_uname;
validuser[c][1] = user_pwd;
validuser[c][2] = "normal_user";
c++;
} while (c < 3);
c = 0;
do{
cout << validuser[c][0] << " " << validuser[c][1] << " " << validuser[c][2] << endl;
c++;
} while (c < 3);
cin >> pause;
}

Related

Transversing an Array of structs error in C++

Current code:
const int MAX_CODENAME = 25;
const int MAX_SPOTS = 5;
struct Team {
string TeamName[MAX_CODENAME];
short int totalLeagueGames;
short int leagueWins;
short int leagueLoses;
};
//GLOBAL VARIABLES:
Team league[MAX_SPOTS];
void addTeams(){
int i = 0; //first loop
int j; //second loop
while(i < MAX_SPOTS){
cout << "****** ADD TEAMS ******" << endl;
cout << "Enter the teams name " << endl;
scanf("%s", league[i].TeamName) ;
}
void searchTeam(){
string decider[MAX_CODENAME];
cout << "Please enter the team name you would like the program to retrieve: " << endl;
cin >> decider[MAX_CODENAME];
for(int i = 0; i < MAX_SPOTS; i++){
if(decider == league[i].TeamName){
cout << endl;
cout << league[i].TeamName << endl;
break;
}else{
cout << "Searching...." << endl;
}
}
}
I really dont know why its not working but I have included all the perquisite header files such as and but the program crashes when i enter the data and then attempt to search. I get the circle of death and then program not responding then says Process returned 255 (0xFF) . It does not even out put Searching.... the program practically gives up as soon as I enter that name.
Also if this can be optimized by the use of pointers that would be great.
tl;dr run-time error causing the search to fail as soon as i type in a name. And for the record I have checked to make sure the name I entered is valid.
scanf doesn't know about std::string. Use std::cin >> league[i].TeamName.
scanf("%s", league[i].TeamName) ;
This should be changed to
std::cin >> league[i].TeamName ;
A couple of other things here....
string decider[MAX_CODENAME];
cout << "Please enter the team name you would like the program to retrieve: " << endl;
cin >> decider[MAX_CODENAME];
Every time you input a value, you are telling the computer to hold the inputted value at decider[25] but the computer only reads indexes 0-24.
if(decider == league[i].TeamName){
Which array slot are you comparing the team name to? If its the 25th element than the statement should be
if(decider[24] == league[i].TeamName){
Pointers are better suited if the number of TeamNames are unknown. Based on the limited code presented, I highly recommend you stay within the realm of basic data types. For the purposes of troubleshooting, please post your full code in the future.
Your TeamName member variable:
string TeamName[MAX_CODENAME];
is an array of 25 strings, so in this line:
scanf("%s", league[i].TeamName) ;
you are courrupting the array. You don't really want an array anyways, so change the TeamName declaration to:
string TeamName;
and then when you read the name, you'll need to use iostreams which knows how to populate a string type (scanf only works with c char arrays):
std::cin >> league[i].TeamName

filling a char array with a string? c++

I need to fill this array via user prompt. I was thinking to read in the user entry to a string and then assign that string to the array but that doesn't seem to be the right way to approach this. Could someone help me out?
The error I'm receiving reads "array type array[100] is not assignable"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string.h>
using namespace std;
int main()
{
string theString;
char array[100]; // ARRAY MAX SIZE
int length = sizeof(array)-1;
char * ptrHead = array;
char *ptrTail = array + length - 1;
//USER PROMPTS & ARRAY FILL
cout << "Please enter a string to be reverse: " << endl;
cin >> theString;
array= theString;
//WHILE LOOP SWAPPING CHARACTERS OF STRING
while (ptrHead < ptrTail)
{
char temp = *ptrHead;
*ptrHead = *ptrTail;
*ptrTail = temp;
ptrHead++;
ptrTail--;
}
cout << array << endl;
return 0;
}
arrays are not assignable. You should use strcpy here:
But for this you'll have to convert theString to C like string.
strcpy(array, theString.c_str() );
Then adjust your ptrTail pointer too , like following :
int length = theString.size();
char *ptrTail = array + length - 1;
See Here
cin >> array; should put the input directly into the array, which I'm guessing is what you want
Also, there's a problem in your string reversal logic. You are reversing the entire array, not just the part that has been filled, which will put the filled portion at the end of the array. Consider using a function like strlen() to find out how long the actual input is.
You can copy the string to the array with strcpy or input the data directly to the array with cin >> array, but the better solution would be just not to use a char array, just use the string in your algorithm. That is also a better solution because you can overflow a fixed size char array
cout << "Please enter a string to be reverse: " << endl;
cin >> theString;
for (unsigned int i = 0; i <= theString.size() / 2; ++i)
swap(theString[i], theString[theString.size() - 1 - i);
cout << theString<< endl;
Edit
The same using pointers:
std::cout << "Please enter a string to be reverse: " << std::endl;
std::cin >> theString;
char* i = &theString[0];
char* j = &theString[theString.size() - 1];
for (; i < j; ++i, --j)
std::swap(*i, *j);
std::cout << theString << std::endl;

comparision strings from struct in if statement

I wrote a c++ code and used struct, I want to compare two string in struct type.but error occures:
#include <iostream>
using namespace std;
#define NumOfStudents 2
#define NumOfCourses 3
struct Student{
int stdnum, FieldCode, age;
double average, marks, res[NumOfCourses];
char Fname[20], Lname[20], cmp[20];
};
int main(){
struct Student students[NumOfStudents];
int i, j;
// char cmp[20];
cout << "\t **********************************************************************\n";
cout << "\t *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*\n";
cout << "\t *+ FIRST-NAME || LAST-NAME || STUDENT-NUMBER || FIELD-CODE || AGE +*\n";
cout << "\t *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*\n";
cout << "\t **********************************************************************\n";
for(i=0; i<NumOfStudents; i++){
cout << "STUDENT #" << i+1 << ": ";
cin >> students[i].Fname >> students[i].Lname >> students[i].stdnum >> students[i].FieldCode >> students[i].age;
}
cout << "what student do you want?[Enter family]\n";
cin >> students[j].cmp;
for(i=0; i<NumOfStudents; i++){
if(students[j].cmp == students[j].Lname){ //The error occurs here
for(j=0; j<NumOfCourses; j++){
cout << "\nCOURCE #" << j+1 << ": ";
cin >> students[j].marks;
}
}
else
cout << "The Student with name " << students[j].cmp << " doesn't exist!!!";
}
return 0;
}
In the code I commented place the error occurred...
thank you
Of course this comparison
if(students[j].cmp == students[j].stdnum){
is invalid because data member cmp has type char[20] and stdnum has type int. It is not clear what you are going to compare.
EDIT: I see you updated your post and wrote
if(students[j].cmp == students[j].Lname){
However this statement is also invalid because arrays have no the comparison operator. In this condition the both arrays are converted to pointers to their first elements and the pointers are compared. So the condition will be equal always to false. Instead you have to use strandard C function strcmp
if( std::strcmp( students[j].cmp, students[j].Lname ) == 0 ){
It would be simpler if you would use std::string instead of character arrays. You need to include header <string>
In this case the structure will look the following way
struct Student{
int stdnum, FieldCode, age;
double average, marks, res[NumOfCourses];
string Fname, Lname, cmp;
};
and you could use the comparison operator
if( students[j].cmp == students[j].Lname ){
This should do the trick for you.
if(strcmp(students[i].cmp, students[i].Lname) == 0)
If you are sure about using char string, you should use strcmp function to compare them.
(http://www.cplusplus.com/reference/cstring/strcmp/)
You are using a variable j which has no value assigned to it. Because of that, you are accessing an unknown member in the array, probably something off the array's boundaries (an index larger than NumOfStudents).
I think you want if(students[i].cmp == students[i].stdnum){ instead of if(students[j].cmp == students[j].stdnum){, still, it should be noted that you are comparing two char arrays, which does not have your intended effect of comparing the two strings. It will probably compare the position of the arrays in the memory(will always evaluate to false). Instead use strcmp, and use commands from the <cstring> library when dealing with cstrings (char arrays).
Or just save yourself the trouble and use the string class, which overloads the = operator and lets you compare two strings using =.

c++ c-strings, strncat, strncpy

This program is supposed to input someones name and output it like " Last, first middle". The names are supposed to be stored in 3 different arrays and their is a fourth array for the full name at the end. I am also supposed to use strncpy and strncat to build the fourth array. My issue im having is i dont know what the use of strncpy would be in this situation and how to use it. I can make the program say "first middle last" but not the correct output. Another issue im having is the while loop is supposed to allow the user to say 'q' or 'Q' and quit the program but it doesnt do this
#include <iomanip>
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
char replay; //To hold Q for quit
const int SIZE = 51;
char firstName[SIZE]; // To hole first name
char middleName[SIZE]; // To hold middle name
char lastName[SIZE]; // To hold last name
char fullName[SIZE]; //To hold the full name
int count = 0;
int maxChars1;
int maxChars2;
cout << "Enter Q to quit or enter your first name of no more than " << (SIZE - 1)
<< " letters: ";
cin.getline(firstName, SIZE);
while(firstName[SIZE] != 'Q' || firstName[SIZE] != 'q')
{
cout << "\nEnter your middle name of no more than " << (SIZE - 1)
<< " letters: ";
cin.getline(middleName, SIZE);
cout << "\nEnter your last name of no more than " << (SIZE - 1)
<< " letters: ";
cin.getline(lastName, SIZE);
maxChars1 = sizeof(firstName) - (strlen(firstName) + 1);
strncat(firstName, middleName, maxChars1);
cout << firstName << endl;
maxChars2 = sizeof(lastName) - 1;
strncpy(firstName, lastName, maxChars2);
lastName[maxChars2] = '\0';
cout << lastName << endl;
}
system("pause");
return 0;
}
Your while loop doesn't work because of several reasons:
You're actually looking one past the end of the firstName array (firstName[SIZE]) rather than the first character (firstName[0]).
You're not checking to make sure firstName is only a single character q or Q.
You're only asking for the first name one time, before the loop, instead of every loop.
Your call to strncpy doesn't look right. As written, you're taking the last name and copying it to firstName, destroying the first and middle names that you just concatenated together there. Like #steve-jessop said, assemble the full name in fullName.
You're probably supposed to use strncpy and strncat because this is a contrived example/exercise where the buffer taking the full name is of a restricted size, so some name combinations will not fit, and need to be truncated.

C++ program to accept multiples inputs and put in an array using pointer

there's a problem facing me in this question :
"write a c++ console program to accept five
integers values from keyboard in one line separated by spaces . the program then stores the five values in an array using pointer . then print the elements of the array on the screen ."
I tried to make a string variable and accept 5 integers from user then convert it to integer but it doesn't work well because it doesn't take numbers after space .
any help guys ??
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
string numbers;
getline(cin, numbers);
int arr[5];
int *ptr;
int values;
stringstream convert(numbers);
convert >> values;
cout << values;
}
It will only take one at a time, you need to add more calls to convert like so:
stringstream convert(numbers);
convert >> values;
cout << values;
convert >> values;
cout << " " << values;
convert >> values;
cout << " " << values;
The C++faq has a good section on this.
Without major modification, if you need to put the number directly into the array using a pointer, you can do this:
int *ptr = arr ;
convert >> *ptr++ ;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
for( unsigned int i = 0; i < 5; ++i )
{
cout << arr[i] << " " ;
}
cout << std::endl ;
I successfully made it
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
int arr[5];
string number;
cout << "Please enter 5 integers separeted with spaces " << endl;
getline(cin, number);
int *ptr = arr ;
stringstream convert(number);
convert >> *ptr++ ;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
for( int i = 0; i < 5; ++i )
{
cout << arr[i] << " " ;
}
cout << std::endl ;
}
I the numbers variable is string you can search for first non space character using numbers.find_first_not_of(" "); and first space character by numbers.find_first_of(" "); then create a subset using substr(.....) now place the substr in another string variable. Now convert the substring to int. repeat the steps for number of times you need. i.e. place the whole code inside a while loop. Terminate the loop whenever numbers.find_first_of(" ");returns numbers.end()