variable changes itself or I'm an idiot (probably I'm an idiot)

I was messing with this code but it just won't work.
The code should convert every letter I type in in numbers referring to its position in the alfb array. When I print x (the converted letter) it always works except it immediately changes itself to -1. That means that the letter wasn't recognized (look at the "search" function). It's like the for loop runs itself again skipping the scanf. I don't know what to do. Please help me!

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
#include <iostream>
#include <iomanip>
#include <cstdio>
#define A 30 
using namespace std;

int search(char arr[],int len,char num){
 
     int i;
	 for(i=0;i<len;i++){
		 if(arr[i]==num){
			 return i;
             break;
          }
      }
    
    return -1;
}

int main() {
	int x,ii,defalf;
	char input,alfb[A] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ','?','.',','};
	std::string msg;
	defalf = 0;
	for(ii=0;ii<A;ii=ii+1) {
			scanf("%c",&input);
			x = search(alfb,A,input);
		cout << "\n" << x << "\n";
	}	
	system("pause");
}
Hey, look into learning how to debug asap, you'll save yourself a lot of time and headaches, it's as important as programming.

No, it's not changing itself, nor are you stupid. The reason is that scanf is being skipped - https://www.google.se/?gfe_rd=cr&ei=Wf-8Vs-bFamr8wecp5HYBQ&gws_rd=ssl#q=scanf+being+skipped

add a \n and it should solve the problem - scanf("\n%c", &input);
Last edited on
Thanks, now it works. I'll definitely look into debugging, seems useful. Thank you once again!
Also:

When using any of the scanf functions, always make use of the return value to see that it worked.

Try not to mix C and C++, I know it's hard to make the change. Consider looking at std::cin it's a basic thing in C++.

Also consider using std::string rather than char arrays, one can still use a subscript to get at the individual chars in the string, plus there are many other benefits :+) .

A for loop looks like this:

1
2
3
for (int i = 0; i < A; ++i) {

}


Avoid using a #define for variables, inside main() make them a const variable instead:

const int A = 30;

ii is not a good name for a variable IMO. Try to use descriptive names for variables and functions, don't abbreviate everything.

If you set your editor to use 4 spaces instead of tabs, it will display better here, the tabs are 8 spaces on this site.

Good Luck !!
Thanks!
Topic archived. No new replies allowed.