I want to let the user to input the string,but the error occur.
Is there another ways to change a whole string but not change it one by one
such as sentence[0] = "H"; sentence[1] = "i" ?
Re: etrusks
Yes, it said:
Write a function that accepts a pointer to a C-string as an argument and capitalizes the first character of each sentence in the string.
Why does your function capital(char*) contain input? It is supposed to operate on its argument, not get additional data from elsewhere.
Your line 8 should make your compiler complain. The "Hello" is a constant string literal and variable 'sentence' stores its address. The memory area is const. A non-const pointer to it is no longer acceptable.
Do you have to write the main()? Is it enough to write the function?
(User input of unknown length requires dynamic memory management; but not within the function.)
Oh, your actual question:
A C-string is an array of char elements, where element value 0 indicates end. Like any array, you do access individual elements. You need a search routine to find the first character of each sentence (or reaches the end of the string). You only need to change the first character of each sentence, not every element.
If you want to use char array to store your sentence you have to allocate char array at 1st where you will store chars what you read. You have to figure out some good size, in the example its 1000 to store 1 sentence.
#include <iostream>
#include <cctype>
int get_capitalized_sentence(char* sentence, int maxsize); //maxsize represents max size in buffer
int main()
{
constexprint buffer_size = 1000;
char buffer[buffer_size]; //creating char array with 1000 elements
while(get_capitalized_sentence(buffer, buffer_size) > 0){
std::cout << "Transformed sentence : " << buffer << '\n';
}
}
int get_capitalized_sentence(char* sentence, int maxsize)
//return 0 if EOF occured and nothing was read
{
std::cout << "Please input some sentence." << std::endl;
//first skip whitespaces and get the 1st char of the sentence
unsigned index = 0; //index representing position of current char read
char ch;
std::cin >> ch;
if(std::cin) //if operation was successful
sentence[index++] = std::toupper(ch); //first letter will be capital letter, reposition indexto next element
for(; std::cin.get(ch) && ch != '.' && index < maxsize - 2; ++index) //get the rest of chars till EOF or (.) or till buffer is full
sentence[index] = ch;
if(ch == '.') //if input was terminated by . add it to buffer
sentence[index++] = '.';
sentence[index] = '\0'; //add terminating 0
if(!std::cin) std::cin.clear(); //in case cin is in bad state clear it
return index; //return index to know if any sentence was read and how long was it
}