Code is supposed to take the input for the size of the array and a set of characters and output them as uppercase. My problem is that when I input a sentence like "i love chocolate" its returning ILOVECHOCOLATE. Is the issue how I am grabbing the input? Or am I losing the spaces else where?
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
void readString(char*, int);
void changeToUpper(char*, int);
void displayString(char*, int);
int main()
{
int arraySize;
char* characterArray;
cout << "Enter the size of dynamic array: ";
cin >> arraySize;
characterArray = new char[arraySize];
readString(characterArray, arraySize);
changeToUpper(characterArray, arraySize);
displayString(characterArray, arraySize);
delete[] characterArray;
system("pause");
return 0;
}
void readString(char* characterArray, int arraySize){
cout << "Enter a string of " << arraySize << " characters to be changed:";
for(int i= 0; i < arraySize; i++){
cin >> characterArray[i];
}
}
void changeToUpper(char* characterArray, int arraySize){
for(int i = 0; i < arraySize; i++)
characterArray[i] = toupper(characterArray[i]);
}
void displayString(char* characterArray, int arraySize){
cout << "\nYour string Upper Cased: ";
for(int i = 0; i < arraySize; i++)
cout << characterArray[i];
cout << endl;
}
You can use fgets
fucntion of <csdio>
header file.
The parameter of this function is char*
and length including \0
and FILE*
.
This function is finished only by \n
character. You can include whitespace
character.
But When u input a size of array, last character is \n
. so u must clear that character.
getc
function reads 1 character from FILE stream
. By doing this, u skip \n
happend from input of array size.
So these codes are changed.
#include <cstdio>
cin >> arraySize; getc(stdin);
void readString(char* characterArray, int arraySize){
cout << "Enter a string of " << arraySize << " characters to be changed:";
fgets(characterArray, arraySize, stdin);
}