1. How do you read names that might or might not contain spaces? 2. How do you s
ID: 3840824 • Letter: 1
Question
1. How do you read names that might or might not contain spaces?
2. How do you store multiple (C)strings together in a single variable?
3. How do you sort (C)strings? (Hint: Most books/sites discuss sorting with respect to numbers. What might you need to modify for sorting (C)strings?)
4. How can you access a single row of a 2D array?
5. Can you pass a single (C)string from an array to, say, strcmp?
6. How can your 'again' question accept either characters or words? How can it be case insensitive?
Explanation / Answer
1. How do you read names that might or might not contain spaces?
we can use getline() function to read the characters which will read until newline character is found
2. How do you store multiple (C)strings together in a single variable?
we can use 2D arrays to store multiple c strings
char words[20][50]; // this is capable of storing 20 words each of 50 character length
3. How do you sort (C)strings?
4. How can you access a single row of a 2D array?
Suppose a 2D array is defined as,
int array[20][2];
5th row is accessed by entering 5 in the first subscript and then using 0 and 1 in the next to access the elements in the particular location.
array[5][0] and array[5][1] // array elements start at index 0. So when you declare an array of 20 numbers indexing will be from 0 to 19.
5. Can you pass a single (C)string from an array to, say, strcmp?
Yes, This is a working example:
#include <iostream>
#include <cstdlib>
#include <string.h>
using namespace std;
int main() {
char array[4][10] = {"Hello", "World", "Mine", "Dear"};
printf("%d", strcmp(array[0], array[2]));
return 0;
}
6. How can your 'again' question accept either characters or words? How can it be case insensitive?
char *choice = "yes";
while(strcmp(choice, "yes") == 0)
{
......... // body of the loop
scanf("%s", &choice); // getting the choice again from user
for(i = 0; i < strlen(choice); i++)
choice[i] = tolower(choice[i]); // we can check for both cases by simply converting the input to lowercase completely
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.