Program got stuck , not printing output [closed] - c++

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

Related

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++ vector : initializing with cin in a loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 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'm new to programming and i have problem with some items
i would appreciate any help
first i started initializing the vector as followed but i couldn't end the loop with Ctrl+Z
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector <double> temps;
double temp;
cout << "Enter a sequence of tempreatures : " << "\n" ;
while (cin >> temp){
temps.push_back(temp);
}
double sum = 0;
for (int i = 0; i< temps.size(); ++i)
sum += temps[i];
cout << "Mean temprature : " << sum / temps.size() << "\n";
sort(temps.begin(), temps.end());
cout << "Median temprature : " << temps[temps.size() / 2];
then i changed the while into this format :
cout << "ENter a sequence of tempreatures ending in 1500 : " << "\n" ;
while (cin >> temp){
if (temp == 1500)
break;
temps.push_back(temp);
}
now i have this error
"vector subscript out of range"
apparently break does not work properly here
what should i do?
Your issue is in the check condition of for loop.
for (int i = 0; i, temps.size(); ++i)
sum += temps[i];
It should be
for (int i = 0; i < temps.size(); ++i)
i, temps.size() will evaluate and then ignore the part before , and are left with temps.size() as check condition which will always be greater than 0 if you push_back at least one element and your loop will never end.You might want to read how ,(comma) works.
If you switch to std::getline into a string instead of std::cin into a double, you can check whether the input is empty:
std::string input;
std::getline(std::cin, input);
while (!input.empty()){
temps.push_back(atof(input.c_str()));
std::getline(std::cin, input);
}
If you also fix the for-loop as mentioned by Gaurav Sehgal, it works fine (Enter all numbers then hit enter without any input).
If you are on windows then you have to do
CTRL + Z
If you are on Unix based(Linux/Mac) then you have to do
CTRL + D
This will give the end of file signal and you will be able to break the loop

std::sort function not working in char array [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 5 years ago.
Improve this question
i was extracting lowercase and uppercase characters from a string . then print those uppercase and lowercase string in sorted order in .to sort the string i used std::sort function .but it's not working.
here is my code
#include <bits/stdc++.h>
using namespace std;
int main() {
//std::ios::sync_with_stdio(false);
char str[1005];
char low[1005];
char upr[1005];
int n;
int t;
cin>>t;
while(t--)
{
cin>>n;
cin>>str;
low[0]='\0';
upr[0]='\0';
int i=0,j=0,k=0;
while(i<n)
{
(str[i]>='A' && str[i]<='Z') ? (upr[j]=str[i],++j) : (low[k]=str[i],++k) ;
++i;
}
low[j]='\0';
upr[k]='\0';
cout<<"lowercase="<<low<<'\n';
cout<<"uppercase="<<upr<<'\n';
sort(low,low+j);
sort(upr,upr+k);
cout<<"lowercase="<<low<<'\n';
cout<<"uppercase="<<upr<<'\n';
}
return 0;
}
test case:
1 // number of test cases
15 // length of string
abHJUdjKIpwlaKm
output:
lowercase=abdjpw //before sorting
uppercase=HJUKIK //before sorting
lowercase=abdjpw //after sorting
uppercase= //after sorting
after sorting uppercase string don't even print.
You have a bug with indexes, fix:
low[k] = '\0';
upr[j] = '\0';
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';
sort(low, low + k);
sort(upr, upr + j);
cout << "lowercase=" << low << '\n';
cout << "uppercase=" << upr << '\n';
Exchanged k and j in this snippet.
Better variable names would help. Try replacing j and k with something more descriptive like lowIndex and uprIndex. Then you should see the problem.
I noticed you were using j variable for uppercase and k for lowercase in the while loop then proceeded to do the opposite later. Was this intentional? Wondering if that's causing a bug.

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

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]);

C++ char to string acting funky [closed]

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 6 years ago.
Improve this question
This is the code:
int main(){
string word= "word";
char ciphered[word.length()];
for(int i=0; i<word.length(); i++)
{
int current_position = (int) word[i];
int new_position = current_position + 2;
char this_char = (char) new_position;
ciphered[i] = this_char;
}
string str(ciphered);
cout << str << endl ;
}
When i run this it prints this:
But when i do this:
for(int i = 0; i<sizeof(ciphered); i++)
{
cout << ciphered[i] << endl ;
}
it prints out the same thing but without last three signs and that is correct
but whenever i try to convert this char array to string it adds these last three weird signs and i dont know why
First of all, this:
char ciphered[word.length()];
is not legal C++ code, though gcc may accept it. But second that you do not need really that char array, as you can access individual symbols with std::string itself:
string word= "word";
string ciphered( word.length(), ' ' );
for(int i=0; i<word.length(); i++)
{
ciphered[i] = word[i] + 2;
}
cout << ciphered << endl;
your code prints additional symbols because you did not put null terminator on C-style string and sent it through std::ostream which leads to UB and prints garbage that happens in memory after your char array until it suddenly finds null terminator or crash because of access of invalid memory.