Unable to store value in array in c++ - c++

What i'm willing to do is i wanna convert all the values of the array to their respective ASCII values and then store them in another array. My code is able to convert the character values into ASCII but it fails in storing them in another array. Please help me out.
#include <iostream>
#include <string>
using namespace std;
int main(){
char ass[10];
char name[]= "Chaitanya";
int size=sizeof(name);
for(int i=0; i<size; i++){
int p=name[i];
cout<<p<<"\n";
for(int j=0; j<size; j++){
ass[j]=p;
}
}
return 0;
}
When I try to run this program I get the following error message:
warning: variable ‘ass’ set but not used [-Wunused-but-set-variable]
Thank You!
I got the previous one. But what if i wanna print all those elements stored in ass once again. I'm using the following code and it does nothing. I'm not getting any error.
#include <iostream>
#include <string>
using namespace std;
int main(){
char ass[10];
char name[]= "Chaitanya";
int size=sizeof(name);
for(int i=0; i<size; i++){
int p=name[i];
cout<<p<<"\n";
for(int j=0; j<size; j++){
ass[j]=p;
}
}
for(int q=0; q<size; q++){
cout<<ass[q];
}
return 0;
}

Your warning is not a failure. It's just pointing out that once you store it, you never use it!

Your warning is just telling you that you aren't using the variable ass. It's not an error, but you do have a problem in your code:
int size = sizeof(name);
for (int i = 0; i < size; i++)
{
int p = name[i];
for (int j = 0; j < size; j++)
{
ass[j] = p;
}
}
The second for loop will simply overwrite each character in ass with the single character p. A nested for loop isn't needed, just assign the character from the main loop:
for (int i = 0; i < size; i++)
{
int p = name[i];
ass[i] = p;
}
Moreover, this can be facilitated through the Standard Library functions. For example:
#include <iostream>
#include <string>
int main()
{
std::string ass;
std::string name = "Chaitanya";
for (auto a : name)
{
std::cout << static_cast<int>(a);
}
ass = name;
std::cout << ass; // "Chaitanya"

warning: variable ‘ass’ set but not used [-Wunused-but-set-variable]
This warning just say that you have set the variable ass but you never use it. It is not an error at all.
As an example, try to output a value for this array and the warning will disappear:
std::cout << ass[0] << std::endl;
There is a little part on this warning here: http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html.

The warning is correct, you only set the values of ass you do not use the values set afterwards. If you added let's say a cout after the loop the warning would go away:
std::cout << ass[0] << std::endl ;
I also, don't think you need the second inner loop, if you want to print out each element of ass you could add it that after you set it. So the fix and additions print out could look like this:
for(int i=0; i<size; i++)
{
int p=name[i];
cout<<p<<"\n";
ass[i]=p;
std::cout << ass[i] << std::endl ;
}

Related

How can I fix my code so I don't get a C6385 warning?

I'm having trouble with a C6385 warning in my code. I'm trying to see if two arrays will equal each other. The warning I keep getting is on the line where if(p[i] == inputGuess[j]). I have tried redoing these line but I keep getting the same warning. Does anyone know what I'm doing wrong. This is also my first time programming in C++.
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "Game.h"
#include <iostream>
#include <iomanip>
using namespace std;
int* generateNumbers(int n, int m) {
// Intialize random number
srand(static_cast<unsigned int>(time(NULL)));
// Declare array size to generate random numbers based on what is between 1 to (m)
int* numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = (rand() % m) +1;
cout << numbers[i]<< " " << endl;
}
return numbers;
}
void Game::guessingGame(int n, int m) {
int* p;
int sum = 0;
// Call the generateNumber function
generateNumbers(n, m);
// Declare array based on user guesses
inputGuess = new int[n];
p = generateNumbers(n,m);
for (int i = 0; i < n; i++) {
cin >> inputGuess[i];
}
// See if the user guesses and computers answers match up
for (int i = 0; i < n; i++) {
for (int j = 0; i < n; j++) {
if (p[i] == inputGuess[j]){ //Where I keep getting the C6385 Warning
sum++;
break;
}
}
}
}
The C6385 warning documentation states:
The readable extent of the buffer might be smaller than the index used
to read from it. Attempts to read data outside the valid range leads
to buffer overrun.
https://learn.microsoft.com/en-us/cpp/code-quality/c6385?view=msvc-160
Your second if statement compares i < n instead of j < n and since i is never modified inside it will run forever. This causes the warning since you’ll access memory out of bounds. Fix the comparison.

Modification of counting sort

The Counting sort below sorts elements based on their ASCII value.
The code below works fine but I want to do some I/O modification. The code doesn't take custom input.
I tried to do some changes but getting undefined behavior. My first doubt is why I'm getting undefined behavior. secondly, Please provide me with the code which will make the below code run as expected. The comment portion is what I tried by myself.I want it to take input from user.
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
#define RANGE 255
void countSort(char arr[]) //void countSort(char arr[],int n)
{
char output[strlen(arr)]; //char output[n];
int count[RANGE + 1], i;
memset(count, 0, sizeof(count));
for(i = 0; arr[i]; i++) {
count[arr[i]]++;
}
for (i = 1; i <= RANGE; ++i) {
count[i] += count[i-1];
}
for (i = 0; arr[i]; ++i) {
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}
for (i = 0; arr[i]; ++i) {
arr[i] = output[i];
}
}
// Driver code
int main()
{
char arr[] = "geeksforgeeks";
countSort(arr);
cout<< "Sorted character array is "<<arr;
/*
int n;
cin>>n;
char arr[n];
for(int i=0;i<n;i++) {
cin>>arr[i];
}
countSort(arr,n);
for(int i=0;i<n;i++) {
cout<<endl<<arr[i];
}
*/
return 0;
}
So the OP asked, how to take an input from the user and sort this. And not a predefined string in a given char array.
I will give the answer. But the question is tagged with C++, and I will convert it to C++.
By the way. The code in the question is a one to one copy from GeeksforGeeks and tries to code the so called Counting Sort algorithm in C++ that is described here.
Since the code is taken from GeeksforGeeks I unfortunately need to blame user "rathbhupendra" for really bad C++ code. I am truly sorry.
The code is using:
C-Style arrays
Variable Length Arrays (Compiler extension. Not C++ compliant)
strlen
memset
#include<bits/stdc++.h> and #include<string.h>
using namespace std
unusal end conditions in for loops for(i = 0; arr[i]; ++i)
char arrays instead of std::strings
a Macro to define an array size (#define RANGE 255)
So, nothing C++.
And now, the answer.
You need to read the string from the user in a variable of type std::string with the function std::getline.
A std::string can be used like a character array. No difference.
Please see the C++ solution:
EDIT
Edited on the comments of MichaelDorgan
#include <iostream>
#include <string>
#include <vector>
constexpr size_t AsciiRange = 256;
// Convert signed char to unsigned size_t type.
inline size_t char2sizet(char c) { return static_cast<size_t>(static_cast<unsigned char>(c)); }
void countSort(std::string& stringToSort)
{
std::vector<size_t> count(AsciiRange, 0U);
size_t i { 0U };
for (i = 0U; i < stringToSort.size(); i++) {
count[char2sizet(stringToSort[i])]++;
}
for (i = 1U; i < AsciiRange; ++i) {
count[i] += count[i - 1U];
}
std::string output(stringToSort);
for (i = 0U; i < stringToSort.size(); ++i) {
output[count[char2sizet(stringToSort[i])] - 1U] = stringToSort[i];
--count[char2sizet(stringToSort[i])];
}
stringToSort = output;
}
int main()
{
std::cout << "\nPlease enter a string:\n\n";
// Get the string from the user
std::string inputString{};
getline(std::cin, inputString);
// Sort it by characters
countSort(inputString);
// Show result
std::cout << "\n\n\nString sorted by characters is:\n\n" << inputString << '\n';
return 0;
}
Hope this helps . . .
I geuss by 'getting undefined behavior' you meant segmentation fault which sometimes occured. The problem lies in this line
for(i = 0; arr[i]; i++)
instead you should write
for(i = 0; i < n; i++)
You can check that in the first case at the end of each loop arr[i] is sometimes some weird character(this character doesn't belong to the input string) and count[arr[i]] for this char returns negative number which produce segmentation fault here
output[count[arr[i]]-1] = arr[i];

C++ program ( print out n words in alphabetical order ) runtime error

I recently started to learn C++ programing, and watched many of your posts and answers with interest when my mind would lack the creativity. I have a few issues with this code right here. Basically it should show "n" words in alphabetical order. "n" being introduce by the user and the words as well. I get a weird error, could someone give me a few hints on what should i do?
#include <iostream>
#include <vector>
#include <string>
int main () {
int n=0;
std::string cuvant;
std::vector<std::string> lista_cuvinte;
std::cout<<" Cate cuvinte doriti sa comparati = "<< std::endl;
std::cin>> n;
for (int i=0; i<n; i++)
{
std::cout<<"cubantul al " << i + 1 <<" -lea = ";
std::cin>> cuvant;
lista_cuvinte.push_back(cuvant);
for (int i=0; i < n; i++)
{
for (int j=i + 1; j < n; j++)
{
if (lista_cuvinte.at(i) > lista_cuvinte.at(j))
{
std::string temp=lista_cuvinte.at(i);
lista_cuvinte[i]=lista_cuvinte.at(j);
lista_cuvinte[j]=temp;
i=i-1;
break;
std::cout<< temp << std::endl;
}
}
}
}
return 0;
}
You are doing a lot things wrong. Simply sorting starts before all data was read in in your code. Code after a break will never executed. And there is no output.
But you can achieve the same result much simpler by using sort from algorithm. I believe your code is only for learning, so it maybe makes sense to do it by hand. Normally it does not :-)
#include <iostream>
#include <vector>
#include <string>
int main () {
int n=0;
std::string cuvant;
std::vector<std::string> lista_cuvinte;
std::cout<<" Cate cuvinte doriti sa comparati = "<< std::endl;
std::cin>> n;
// read data
for (int i=0; i<n; i++)
{
std::cout<<"cubantul al " << i + 1 <<" -lea = ";
std::cin>> cuvant;
lista_cuvinte.push_back(cuvant);
}
// sort data
for (int i=0; i < n; i++)
{
for (int j=i + 1; j < n; j++)
{
if (lista_cuvinte.at(i) > lista_cuvinte.at(j))
{
std::string temp=lista_cuvinte.at(i);
lista_cuvinte[i]=lista_cuvinte.at(j);
lista_cuvinte[j]=temp;
i=i-1;
break;
}
}
}
// output data
for (int i=0; i<n; i++)
{
std::cout << lista_cuvinte[i] << std::endl;
}
return 0;
}
And with std::sort your code in the section sorting reduces to:
// sort data
std::sort( lista_cuvinte.begin(), lista_cuvinte.end());
Thats all!
As a hint to you for writing and finding errors in general: Please use a debugger. Your code simply throws an exception. Your debugger will catch it for you and you go in the backtrace to the point where the error occurs. In your code it was an access out of range from the array, because the data was not read in at this point of execution.
You are starting sorting before completing the input of the words. Your second for (int i=0... loop is inside your first one.

Weird Array Stuff (Array indexes getting values without me setting it)

I am trying to write a sudoku solver.
I got the input almost done, but something strange started happening. On the index [i][9] of int sudoku[i][9], there are numbers present that I have never put there.
For example, when I run the code below with the input that is commented below using namespace std;, the output is:
410270805
085146097
070580040
927451386
538697412
164328759
852704900
090802574
740965028
Of course, I only need 0 through 8, but I was wondering what is causing integers to appear at the 9th index.
This is the code:
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
/*
410270805
085146097
070580040
927451386
538697412
164328759
852704900
090802574
740965028
*/
int main()
{
int sudoku[9][9];
int solving[9][9][9];
int input;
for (int i=0; i<=8; i++) {
cin >> input;
int j;
int k;
for (j=8, k=1; j>=0; j--, k++) {
int asdf = input/pow(10,k-1);
sudoku[i][j] = asdf % 10;
}
}
cout << endl;
for (int i=0; i<=8; i++) {
for (int j=0; j<=9; j++) {
cout << sudoku[i][j];
}
cout << endl;
}
return 0;
}
Accessing elements outside of the defined region of an array is Undefined Behavior (UB).
That means it could:
Allow you to access uninitialized space (what yours is doing hence the random numbers)
Segfault
Any number of other random things.
Basically don't do it.
In fact stop yourself from being able to do it. Replace those arrays with std::vectors and use the .at() call.
for example:
std::vector<std::vector<int>> sudoku(9, std::vector<int>(9, 0));
for (int i=0; i<=8; i++) {
for (int j=0; j<=9; j++) {
cout << sudoku.at(i).at(j);
}
cout << endl;
}
Then you will get a thrown runtime exception that explains your problem instead of random integers or segfaults.
I think I found your problem, at your very last for loop you used j <= 9 instead of j <= 8. You then tried to write (j) leaving the possibility of it writing 9 wide open. Try replacing that 9 with 8.

selection sort array run time error

This is my first time here. I really hope anyone can help me out there. So this is my problem. I keep getting run time error #2 something about a corrupt "arr". But the program runs fine until the end. I can't figure it out.
This is my code:
#include <iostream>
using namespace std;
void main(){
int arr1[3];
int temp;
//INPUT NUMBERS
for (int i=0; i<5;i++)
{
cin>>arr1[i];
}
cout<<endl;
//SORT
for(int c=0;c<5;c++)
{
for (int k=0;k<5;k++)
{
if(arr1[c]<arr1[k])
{
temp=arr1[k];
arr1[k]=arr1[c];
arr1[c]=temp;
}
}
}
for (int m=0; m<5; m++)
{
cout<<arr1[m]<<endl;
}
}
Try this out:
#include <iostream>
using namespace std;
int main()
{
int arr1[5];
int temp;
//INPUT NUMBERS
for (int i = 0; i < 5; i++) {
cin >> arr1[i];
}
cout << endl;
//SORT
for (int c = 0; c < 5; c++) {
for (int k = 0; k < 5; k++) {
if (arr1[c] < arr1[k]) {
temp = arr1[k];
arr1[k] = arr1[c];
arr1[c] = temp;
}
}
}
for (int m = 0; m < 5; m++) {
cout << arr1[m] << endl;
}
}
It compiles properly without any errors. The mistake you had made is in declaring the size of the array. If you want to store 5 in puts, you need to declare an array of size 5. Your code might work, but a good compiler will always give out an error.
The reason being that when you declare an array, you actually create a pointer to the first element of the array. And then, some memory regions are kept for this array, depending on the size. If you try to access an element that is outside these memory regions, you may encounter a garbage value.
Here's your code in ideone.