c++ Program help

Having problem with my code. i keep getting an error towards the bottom of the code. i need the user to enter a word. and with that word convert it to numbers. once i have convert it if it is bigger than 20 i have to add the two digits together and get print out the array that response to it.

example" ALEX
A=1
L=12
E=5
X=23

1+12+5+23= 41 //since its bigger than 20 you add 4 and 1 together so it will be 5. after that you print the 5th element of array


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iomanip>
#include <iostream>
#include <string>

using namespace std;

int main()
{
	
	string name;
	int sum = 0;;
	string s[1000]= {"stuff","Stuff", "stuff","stuff", "printStuff"};
	
				
	
cout << "Enter word: " << endl;
getline(cin,name);

cout << "Hello: " << name << endl;


for (int i=0; i<name.length (); i++)
{
	 
	cout<< toupper(name[i]) - 64<< " ";
    sum=sum + toupper(name[i]) - 64;
	 
	 

	string number;
	sprintf(sum,"%d",number);
	for(int k=0; k<number.length(); k++)
	{
	cout << "it has been added your new number is" << number[k];
	}
	
	
}
 cout << "stuff that prints out: " << s[k];

return 0;
}

Just from looking at the bottom since you said at the bottom, you may be talking about...

cout << "stuff that prints out: " << s[k];

You see that k? Where is it originally from?

It's from the for loop above it. That k solely exists inside that for loop. You can't try to reference it outside of that loop.

Also you might run into some trouble with

sprintf(sum,"%d",number);

You specified that the "sum" inside of the sprintf's parameters was an int eariler on in your code.

sprintf has these parameters though, "int sprintf ( char * str, const char * format, ... );"

You are attempting to put an integer in a character's only place.
Last edited on
1
2
3
4
5
6
7
8
//<numeric>
std::cout<<std::accumulate(name.begin(),name.end(),0,[](int x, int y)->int{
            if(y!= static_cast<int>(' ')
               && std::toupper(y) - 64 > 0
               && std::toupper(y) - 64 < 27)
                return x + std::toupper(y) - 64;
            return 0;
        });

My one line example on the first post you did is hard to read, sure, but if you did some research, std::accumulate adds all values in a stl container (like a string), and I used lambdas for its prend.
The first parameter in the lambdas is the sum (x), the second is the value of the current element (y).

Hopefully now you understand how to put this into loop form.

Just remember to keep your code as short, neat, and as c++ as possible. Like use for(int letter_value: some_string), and for the love of god properly space your code, you can use a plugin in your ide to format it for you, like for code::blocks there's AStyle.
Topic archived. No new replies allowed.