Nathaniel Lindsey
Nathaniel Lindsey

Reputation: 135

Take a character from a string and convert it to int in c

I'm new to c and trying to write a console application that takes the time signature and BPM information from a user's musical project and returns the length of one bar in seconds.

I want to take the user input string for time signature (example: "4/4"), isolate the first character (a numeral representing the number of beats per bar), and transform it into an integer to be used in the calculation.

The two methods I've tried,

int beatsPerBar = timeSignature[0];

and

int beatsPerBar = atoi(timeSignature[0])

both return the same error: "subscripted value is neither array nor pointer nor vector".

How do I correctly change the variable type of this character?

EDIT:

Using @R-Sahu 's suggestion. The code below compiles and builds with no errors or warnings.

#include <stdio.h>
#include <stdlib.h>

int main()
{

   char timeSignature[4];
   int BPM;

   printf("Enter the working time signature of your project:");
   scanf("%s",&timeSignature[4]);

   int beatsPerBar = timeSignature[0]-'1';

   printf("Enter the beats per minute:");
   scanf("%i",&BPM);

   printf("%i\n", beatsPerBar);

   return 0;

}

However, when I test the code with the following values

timeSignature = "4/4"
    BPM = 180

I get a resulting integer of -47 (calculator check says it should be returning 45).

What am I doing wrong? Clearly my understanding of encoding and the integers used to represent character values isn't where it should be. Can anyone share links to broad tutorials on this subject?

Upvotes: 0

Views: 121

Answers (3)

Shreevardhan
Shreevardhan

Reputation: 12641

No need to use atoi, you can simply convert a char to int. For instance

int beatsPerBar = timeSignature[0] - '0';

Upvotes: 0

Baha
Baha

Reputation: 408

As @r-sahu said:

The input argument type of atoi is const char *

So if you still want to use atoi you can convert the char to a string then use atoi as follows (for example):

if (isdigit(timeSignature[0]))
  char dig[2]= {timeSignature[0],'\0'};
  int beatsPerBar = atoi(dig);

Upvotes: 0

R Sahu
R Sahu

Reputation: 206567

Use of

int beatsPerBar = atoi(timeSignature[0])

should result in a compiler error. The input argument type of atoi is char const*, which timeSignature[0] is not.

int beatsPerBar = timeSignature[0];

is syntactically right but not semantically. That will set the value of beatsPerBar to the integer value used to represent the character 4. If your platform uses ASCII encoding, that value is 52.

You should use:

int beatsPerBar = timeSignature[0] - '0';

to get the number 4 assigned to beatsPerBar.

If you want to be more careful, which you should, you can add the following check.

int beatsPerBar = 0;
if ( isdigit(timeSignature[0]) )
{
   beatsPerBar = timeSignature[0] - '0';
}
else
{
   // Deal with error.
}

Upvotes: 2

Related Questions