How to convert first letter to uppercase in c++? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a Structure
struct StudentRecord{
char StudentFamilyName[20]
}gRecs[50];
cout << "Family Name: ";
cin >> gRecs[50].StudentFamilyName;
char str[20];
str[20] = toupper(gRecs[i].StudentFamilyName[0]);
cout << str;
What i want to do is to store the first letter of family name as
upper case and the rest as lower case? How do I do that?
I used toupper but when I implement it doesnot work. Could anyone help me out? Thank you.
Note: This was an exam question.

Here's how to capitalize a string using character arithmetic:
#include <iostream>
#include <string>
using namespace std;
string ToCapitalize(string input)
{
if (input.length() > 1 && input[0] >= 'a' && input[0] <= 'z')
{
input[0] -= 32;
}
return input;
}
int main() {
std::string StudentFamilyName("smith");
cout << StudentFamilyName << std::endl;
cout << "Capitalized: " << ToCapitalize(StudentFamilyName) << endl;
}

Your problem isn't with toupper. There are a couple of them, actually.
cin >> gRecs[50]
gRecs is size 50, so index 50 is out of bounds. To insert into the first record you would use
cin >> gRecs[0].StudentFamilyName;
Second record: gRecs[1], etc.
Next,
char str[20];
str[20] = toupper(str[0]);
You declare str in which nothing is populated, and then call toupper on it.
And the index ([20]) is the 21st character (which is out of bounds). You are attempting to convert the 21st character in the str toupper.
What you need is something like:
// i is the index into your student records array, possibly in a loop
cin >> gRecs[i].StudentFamilyName;
gRecs[i].StudentFamilyName[0] = toupper(gRecs[i].StudentFamilyName[0]);

Related

Why the loop only run one time? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried to do a phone Sys and I used a while loop in the main{}. I don't know why it only runs one time, it suppose to run infinite time unless I give it command to stop.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void record(string name, int phoneNum, int count);
// main
int main() {
cout << " Welcome to use the Phone Contact Systerm " << endl;
string name;
int phoneNum;
int count = 0;
string signToStop;
cout << " Please enter name and phone number " << endl;
while ( cin >> name >> phoneNum){
cout << " If you want to start the program, enter start " << endl;
cout << " If you want to quit the program, enter quit " << endl;
cin >> signToStop;
if (signToStop == "start"){
record(name, phoneNum, count);
}
else if ( signToStop == "quit" ){
break;
}
count++;
}
}
// record all name info into Name set and record all phone numbers into PhoneNum set
void record(string name, int phoneNum, int count){
string Name[] = {};
int PhoneNum[] = {};
Name[count] = {name};
PhoneNum[count] = {phoneNum};
// now start to record all the info into .txt document
ofstream phoneFile;
phoneFile.open("contact.txt");
phoneFile << name << " " << phoneNum << endl;
}
The result is:
Welcome to use the Phone Contact Systerm
Please enter name and phone number
Molly 5307659229
Process finished with exit code 0
Maybe try ulong int for the phone number, it might be too long. Also I might add that I am a bit confused, as your function record() has a 3rd argument that has no default argument. Your problem might lie there too. As without a default you need to put the argument in when it is used.
As spectras said, a phone number is not really an integer, and so it's not a "number" in the programming (or even mathematical) sense.
It's more like a sequence of digits; that is, a string.
You have two problems when you try to interpret it as an int:
Your int type is too small for the value (this is what's causing your loop to end)
Leading zeroes are not meaningful (at best, it's used to flip into octal mode, which is not what you wanted).
I'd instead read it as a string. You can still validate it later, like "is every character a digit?".

Program got stuck , not printing output [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am a beginner in C++. And I am trying to play with character array in C++. So, I have written this code.
#include <iostream>
using namespace std;
//Main Function
int main()
{
//Variable declaration
char First[30];
char Middle[30];
char Last[40];
//Array to store all names
char Name[70];
//Loop variables
int i = 0, j = 0;
//Reading all the name
cout << "Enter First name: ";
cin >> First;
cout << "Enter Middle name: ";
cin >> Middle;
cout << "Enter Last name: ";
cin >> Last;
//Copies all characters of Last name to fourth array
while (Last[i] != '\0')
{
Name[j] = Last[i];
i++;
j++;
}
//placing a comma in the fourth array and adding a space
Name[j] = ',';
j++;
Name[j] = ' ';
j++;
cout<<"Hello1\n";
//Copies all characters of First name to fourth array
i = 0;
while (First[i] != '\0');
{
Name[j] = First[i];
i++;
j++;
}
//Add a space
Name[j] = ' ';
j++;
cout<<"Hello2\n";
//Copies all characters of Middle name to fourth array
i = 0;
while (Middle[i] != '\0');
{
Name[j] = Middle[i];
i++;
j++;
}
Name[j] = '\0';
//Display the fourth array
cout << Name << endl;
}
The Problem with this code is that i want to print the Full Name of
Name[] array. But it is getting stuck after printing "Hello1" only.
It is not printing anything after "Hello1". It is taking input of all
three names ( in First[] , Middle[] and Last[] ) correctly. So, I
decided to trace out my code from line 1. I got to know that there is
some problem after first while loop as i am trying to print "Hello1"
and "Hello2". The problem is that it is printing "Hello1" correctly
but it is getting stuck for "Hello2". I think that some problem is in
2nd while loop. But i am not getting the error how could i resolve
this.
Please help me regarding this so that it could print the Full Name
correctly.
Ok so, the problem is your while loop, you made the mistake of put a ; in the end of it, which is making an infinity loop and never gets to the second hello.
//Copies all characters of First name to fourth array
i = 0;
while (First[i] != '\0'); // <- Here is your problem
Should be:
//Copies all characters of First name to fourth array
i = 0;
while (First[i] != '\0') { // <- Here is your problem
Edit
Thanks to Gilles-Philippe Paillé who pointed out, in the third while loop also has an semi-colon which should be removed :D

c++ input array of char after input int [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have an array of characters with variable size which is received from user input. From there I input the array with for loop based on the size but it seems like the variable holding the size is changing and I'm stuck in infinite loop.
char arr_1[] = {};
int array_size;
cout << "Array size: ";
cin >> array_size;
for (int i = 0; i < array_size; i++)
{
cout << "Input: ";
cin >> arr_1[i];
}
I have an array of characters with variable size
char arr_1[] = {};
There is no such thing as "array with variable size" in C++. The size of an array never changes. Furthermore the size of non-dynamic arrays must be compile time constant. What you have declared there is an array of size zero. Non-dynamic arrays of zero size are ill-formed.
If the compiler for some reason fails to spot the bug (perhaps it supports zero length arrays as a language extension), then you end up accessing the array outside of bounds. The behaviour of accessing an array out of bounds is undefined. Infinite loop is one example of undefined behaviour.
There is however a standard container that will automatically reallocate a progressively larger array as you insert elements into it: std::vector.
Although, since you're dealing with characters, perhaps they're supposed to represent a character string. There is a special container for that purpose: std::string.
Vector would be more appropriate to use than an array in this case. Even easier is to just work with a string:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numChars = 0;
string word("");
cout << "Num chars you want to input: ";
cin >> numChars;
for (int i = 0; i != numChars; ++i)
{
string input("");
cout << "Enter a char: ";
cin >> input;
if (input.size() == 1)
word += input;
else
{
cout << "Invalid input- exiting";
getchar();
exit(0);
}
}
cout << "Your word: " << word;
getchar();
getchar();
}

C++: Counting the frequency of ASCII characters in file [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am a beginner to C++ and have been pondering this problem for quite a while, but I'm finding myself unable to come up with a solution and was hoping I could find some direction here.
I have an input file that will contain any number of ASCII characters (ex: hello, world; lorem ipsum; etc.). My program will read this file and count the frequency of each ASCII character, outputting the end counts when EOF is reached. I believe I need to use array[128] for the counters, but besides that, I'm totally stuck.
Here's what I have so far (it's not much and only reads the characters from the file):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
ifstream inputFile;
string infile;
char ch;
//char ascii;
//int asciiArray[128] = {0};
// Gets input filename from user, checks to make sure it can be opened, and then
// gets output filename from user.
cout << "Please enter your input filename: ";
cin >> infile;
inputFile.open(infile.c_str());
if (inputFile.fail())
{
cout << "Input file could not be opened. Try again." << endl;
exit(0);
}
// Gets the first character of the input file.
inputFile.get(ch);
while(!inputFile.eof())
{
inputFile.get(ch);
}
// Closes the input file
inputFile.close();
return 0;
}
Any direction or help would be greatly appreciated. I have a feeling I will need to use pointers to solve this...but I've just barely started covering pointers, so I'm very confused. Thanks!
Edit: I removed some variables and it's working now, looks like I forgot them there while I was brainstorming. Sorry for leaving it unworking and not mentioning why; I won't do that again!
You should write your loop as:
while(inputFile >> ascii)
{
asciiArray[ascii]++;
}
Note that I don't directly check for eof in the loop condition since that's almost always wrong.
Also you should be sure that your file is indeed written with ascii characters only. Since any character outside the ascii range would result in an out of bounds access to the asciiArray.
In regular Ascii you have 128 chars... of which each char can be evaluated as an int.
That is the key in solving this puzzle.
Just remember you have 128 possible chars, an array with 128 values, and each char represents a number from 0-127.
Also recall that you can do stuff like this:
int i = 97;
char a = i;
char b = a + 1;
cout << (int)i << (int)a << (int)b << endl;
// 979798
cout << (char )i << (char )a << (char )b << endl;
// aab
cout << i << a << b << endl;
// 97ab
As far as pointers go, the only way I would see them as being used is if you used pointer notation instead of array notation while manipulating your variable asciiArray

In short I really struggle with syntax, can somebody help me fix this? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
so i need to read in a file, then create a word count and a character count for each time the character appears using an array. each word ends with whitespace, comma, period, etc. also i need to put a tolower and an equation to set the letters to the right array with an x-'a' function or something like that.
list of errors from puTTy(crappy program i know but it's required)
project8.cpp: In function âint main()â:
project8.cpp:17: error: âfile1â was not declared in this scope
project8.cpp:18: error: expected â;â before âwhileâ
project8.cpp:36: error: expected â}â at end of input
#include <iostream>
#include <string>
using namespace std;
int in_word = false;
int word_count = 0;
char ch;
char low_case;
int char_count[26];
int i;
int main()
{
for (i=0; i<26; i++)
char_count[i]=0;
cin.get(file1.txt)
while('\n' !=(ch=cin.get(file1.txt)))
{
if (' ' == ch || '\n' == ch || '\t' == ch)
in_word = false;
else if (in_word == false)
{
in_word=true;
word_count++;
}
else low_case=tolower(ch);
char_count[int(low_case)-int('a')]++;
}
cout << file1.txt;
cout << words << " words" << endl;
for (i=0; i<26; i++)
if(count[i] !=0)
cout << count[i] << " " << char(i+'a') << endl;
}
The first problem is that you haven't declared file1. It is somewhat unclear what file1.txt really is meant to be: The way it is written, it seems to be an object of type with a member called, txt of type char* or char[N] (with a constant N). From the looks of it, you actually wanted to open a file named file1.txt. This would look like so:
std::ifstream in("file1.txt");
After that you would, of course, use in instead of std::cin to read from the file. For example you could use
for (char c; in.get(c); ) {
// ...
}
to read each individual character of the file and process it appropriately.
Let's play compiler!
You cannot name a variable file1.txt, call it file1
Also, you forgot the semi-colon ; at the end of the line, so
cin.get(file1.txt)
should be
cin.get(file1);
I don't quite know where you are defining this variable, so you may be missing a declaration like
const char* file1="file1.txt";
Furthermore, you start trying to access some variable count after your for-loop here:
count[i]
Did you mean to use char_count?