Need the following function to read a users name into the destination Function:
ID: 3541669 • Letter: N
Question
Need the following function to read a users name into the destination
Function:
void read(char* destination, int maxChars)
Purpose:
Read a string of characters entered by the user at the keyboard with a length no longer than maxChars (including the null character at the end of the C string) into an address specified by destination The user should be able to type a space or tab as part of the string.
The getline() method of the istream class in the header file <iostream> can be used to read a string that contains spaces or tabs into an array of char.
Explanation / Answer
#include<iostream>
#include<cstdio>
using namespace std;
void read(char* destination, int maxChars) {
int chars = 0;
char c;
while(c = getchar()){
destination[chars]=c;
chars++;
if(chars>=maxChars-1){
destination[chars]='';
break;
}
}
destination[chars]='';
}
int main(){
int x=5;
char* dest;
read(dest, x);
cout<<dest<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.