sscanf cannot detect a number C - c

So I wrote this function in C using sscanf:
int parse_charstar(char *pointah)
{
int numbeh;
int retaahn = sscanf(pointah,"%*[^0123456789]%d",&numbeh);
printf("\n prent deeh numbeeh %d \n",numbeh);
return numbeh;
}
I want to get a number out of a string if there, for eg.
"hello 121"
number: 121
Currently using the above I'm getting garbage values, can someone help?
EDIT:
So I found something interesting today. Apparently, this is what was happening!
My code was never wrong to begin with as pointed out by luoluo and dasblinkenlight.
Problem was how I was calling the program. I'm on linux.
I was calling it as:
parse_charstar("1000");
Output:
prent deeh numbeeh -1634553883
I tried:
parse_charstar(" 1000 "); // added spaces
Output?
prent deeh numbeeh 1000
Spot on.
Now can someone tell me why this happens?
EDIT!!!
Hell with it guys, use strtol , its made for this stuff.
http://www.cplusplus.com/reference/cstdlib/strtol/
Code copied shamelessly from the above page:
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main ()
{
char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
char * pEnd;
long int li1, li2, li3, li4;
li1 = strtol (szNumbers,&pEnd,10);
li2 = strtol (pEnd,&pEnd,16);
li3 = strtol (pEnd,&pEnd,2);
li4 = strtol (pEnd,NULL,0);
printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
return 0;
}

A more restricted version of your sscanf would be
int retaahn = sscanf(pointah,"%*[^0-9]%d%*[^0-9]",&numbeh);
Note that this doesn't change anything in your format string. I have just used 0-9 to mention the range and added a second %*[^0-9] to make things more explicit.
Currently using the above I'm getting garbage values, can someone
help?
Probably because you're not passing the right arguments to the function. Just do a
printf("pointah : %s\n",pointah);
to see what is passed or set breakpoints and debug your program.

So since my code was never wrong, it turns out my problem was how I was calling this function.
This is how I solved it:
I was calling it as:
parse_charstar("1000");
I tried:
parse_charstar(" 1000 "); // added spaces
And it worked!
Check my edit above for more!!

Related

I seem to be losing the end of a string after exiting a for loop in c

I seem to be losing the end of my string after the exit of the for loop in the function below. Any help would be very much appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
char  *get_out_file_name(int in_file_num);
int main(int argc, char *argv[])
{
char* file_name = get_out_file_name(37);
printf("name_final = %s \n", file_name);
free (file_name);
}
char *get_out_file_name(int in_file_num)
{
    const int max_name_length = 3;
    const int file_type_length = 4;
    const char *type_suffix;
    type_suffix = ".jpg";
    int num_remainder = in_file_num;
    char * name_final = malloc(sizeof(char) * (max_name_length + file_type_length + 1));
    for (int i = max_name_length - 1; i >= 0 ; i --)
    {
        printf("i = %d\n",i);
        name_final[i] = num_remainder % 10;
        sprintf (&name_final[i], "%d", name_final[i]);
        printf("name_final[i] = %c \n", name_final[i]);
        num_remainder /= 10;
    }
printf("pre concat[1] = %c \n",name_final[1]);
    strcat(name_final, type_suffix);
  //  printf("name_final %s \n", name_final);
    return name_final;
}
The only place the data is retained is in name_final[0], array index 1 and 2 hold no data after the exit of the for loop.
I'm thinking it's possibly sprintf creates it's own local copy in the for loop or that I'm missing a reference/dereference somewhere. I was hoping someone could clarify.
The output is in the screenshot below. Apologies for the quality of the output screen grab. I'm having to use my phone to post.
I've just had chance to work out this function properly and wanted to give an explanation in case anyone stumbles across this in the future.
When I wrote that code I didn't understand how to convert a char by adding 0. I understand now that we don't actually add the value 0. We add the value 48 as this is the ASCII number/index for 0. All this is due to chars being saved as integers by c.

function prototype in c, compile error

So am trying to learn c by-myself (basically not having any previous experience in any programming language) and now I have some issues with prototyping some of my functions to use in header files.
For the sake of learning I only use the < stdio.h > lib and only use the printf and scanf functions and for now it only prints to console.
I was able to code a working prototype function for my menu that only uses the printf function but the scanf gives me more issues and it just refuses to compile and am having trouble to see where my thinking error is.
my main program:
#include "menu.h"
#include "circlefunctions.h"
#include "input.h"
int main(void){
float diameter;
double straal;
double oppervlakte;
double omtrek;
while(1){
menu();
user_input();
system("cls");
switch(user_input())
{
case 1:
printf(" ----------------------------------------\n");
printf(" Typ de diameter van de cirkel: ");
scanf("%g", &diameter);
printf(" ----------------------------------------\n");
straal = diameter / 2;
oppervlakte = PI * (straal * straal);
omtrek = 2 * PI * straal;
printf(" De straal = %f \n\n", straal );
printf(" De oppervlakte = %f \n\n" , oppervlakte);
printf(" De omtrek = %f \n" , omtrek);
printf(" ----------------------------------------\n");
break;
case 2:
return(0);
case 3:
return(0);
case 9:
return(0);
case 0:
return(0);
}
}
return 0;
}
and the stubborn header:
#include <stdio.h>
void user_input();
void user_input(){
scanf("%d", &user_input);
}
The error that I get while trying to compile is in input.h
the part with; scanf("%d", &user_input);
errorcode: format '%d' expects argument type of 'int ', but argument 2 has type 'void () ()'.
And I also got an error on the switch in the main program that the switch quantity is not an integer. I suspect that this error is related but am not sure. I still have to debug that part but if anyone is willing to point me to the right documentation i would much appreciate it.
And a second question that I have is also related to headers: I have < stdio.h > already included in "menu.h". Would I need to include it again in "input.h"?
(if i understand correctly how the preprocessor works i should not have to include it but I can't find anywhere where this is explained in simple terms unfortunately.)
Edit:
Thank you all for providing valuable information.
#zenith Thank you for your example. I hope you don't mind me asking some more.
I have replaced my code with yours in the "input.h" and it will compile and run now. However the behavior has changed. For some unclear reason i now have to input the choice twice before the program accepts my input. So the 1st input gets ignored after an enter and it will only accept the 2nd input.
Could you perhaps point me in the direction what causes this bug? or perhaps point me to some documentation where this is explained? I don't want to take up to much of you valuable time of-course.
Edit 2
Thanks for the reply and info. I got the bug out and it is working as intended(that was silly of me not to see that).
And to the rest who replied: Ill take your information of-course and also learn from that. Thank you all!
user_input() doesn't return anything, since it's declared void.
But you're trying to use the non-existing return value: switch(user_input()).
This causes undefined behavior.
Additionally, this:
scanf("%d", &user_input);
tries to read an int from stdin and store it in the memory address of the user_input function. Not a good idea. Again, undefined behavior.
What you probably want the function to look like:
int user_input(){
int number; // store user input to this variable
scanf("%d", &number);
return number; // return the user input so that it can be used outside the function
}
If you have header files declared in a previous header file. You will not need to include it again in the subsequent included header files. I tend to not include header files in my local *.h files just for that reason. It avoids circular includes if you declare your includes in the .c files as much as possible.
Your scanf function has as its second argument a function of type void(), void(). Meaning it takes no arguments and returns nothing or "void". I think you want your user_input to be a variable of type 'double' that is filled somewhere, maybe via some user input from the console using a call to 'gets' from stdin.
HTH

wcstok() not working correctly?

I'm trying to get each line in a loop for a wchar_t string using wcstok(), that string is supposed to contain at least two lines, the latest 'wcstok(0, L"\n")' is getting always null result and I'm getting the value of i using printf as 1 only instead of 2 or higher, but the problem got solved when doing #if 0 instead of #if 1.
this is the code below:
wchar_t* w;
wchar_t* line;
int j;
wchar_t**** lines;
int** linescount;
......
int i=0;
#if 1 //problem get solved when changing to #if 0
line = wcstok(w, L"\n");
do{
((*linescount)[j])++;
}while(line=wcstok(0, L"\n"));
(*lines)[annex] = calloc(sizeof(wchar_t**), (*linescount)[j]);
#endif
line = wcstok(w, L"\n");
do{
#if 1 //problem get solved when changing to #if 0
(*lines)[j][i] = calloc(sizeof(wchar_t*), wcslen(line)+1);
wcscpy((*lines)[j][i], line);
#endif
i++;
}while(line=wcstok(0, L"\n"));
printf("i = %d\n", i); /*prints the i value to check if the latest line=wcstok(0, L"\n") worked correctly or not*/
so what's supposed the cause of this problem? and how can I solve it? please help.
The wcstok modifies the string passed in as argument so once you have run your loop to count lines the buffer is basically kaputt.
It seems like overkill to use wcstok to count lines when you easily could just loop through the buffer counting number of \n.

short function in c - don't understand what's wrong

I'm writing a function that just calculates the "complementary" strand of DNA, meaning replaces C with G, T with A, and so on.
this is what I wrote:
#include <stdio.h>
#include <string.h>
#define SIZE 70
int isLegitSequence(char sequence[]);
void getComplementaryStrand(char complementary[],char sequence[]);
int findSubSequence(char sequence[],char subsequence[]);
int findSubComplementary(char sequence[],char subcomplementary[]);
void cutSequence(char sequence[],char tocut[]);
void checkDNAList(char data[][SIZE],int rows,char sequence[]);
void main(){
char dnaSequence[SIZE];
char compDnaSequence[SIZE];
printf("Enter a DNA Strand\n");
gets(dnaSequence);
printf("%d\n",isLegitSequence(dnaSequence));
getComplementaryStrand(compDnaSequence,dnaSequence);
puts(compDnaSequence);
}
int isLegitSequence(char sequence[]){
int i=0;
while (sequence[i]){
if(sequence[i]=='A'||sequence[i]=='C'||sequence[i]=='G'||sequence[i]=='T');
else return 0;
i++;
}
return 1;
}
void getComplementaryStrand(char complementary[SIZE],char sequence[SIZE]){
int j=strlen(sequence)-1,i;
for(i=0;sequence[i];i++,j--){
if(sequence[i]=='A') sequence[j]='T';
else if(sequence[i]=='C') sequence[j]='G';
else if(sequence[i]=='G') sequence[j]='C';
else sequence[j]='A';
}
complementary[strlen(sequence)]='\0';
}
However, this is what I get when I run the program:
Enter a DNA Strand
CGCTC
1
╠╠╠╠╠
Press any key to continue . . .
This is my first time using functions, so I'm not sure what I did wrong here.
Would appreciate help, but in the scope of my understanding, namely very very basic.
You need to add a prototype of the function getComplementaryStrand at the top of of the source file where the function is called.
Add this line at the top of the source file:
void getComplementaryStrand(char complementary[SIZE],char sequence[SIZE]);
EDIT: the question has changed in the meantime... Before it was a compilation error. OP please ask a new question instead of editing your original question with a new question.
Take a careful look at your for loop within your getComplementaryStrand() function. Are you assigning values to the correct string? I think not.
In getComplementaryStrand() you never fill anything in complementary string except end character. So you get garbage.

print concat value of newline("\n") result shows as <?> symbol in C

I have a code below
#include <stdio.h>
int main()
{
char *price_c = "200";
char *s_att = "test ";
int satt=strlen(s_att);
int price_len = strlen(price_c);
int send_attach_len = price_len+satt;
size_t length = send_attach_len +2;
char *concat = malloc(sizeof(char) *length);
snprintf(concat, length, "%s%s%s", s_att, price_c, "\n");
printf("value of concat is %s", concat);
}
when I see the value printed, I have only test 200 , but on some other occasion, I have test 200 < ? > where < ? > is a weird symbol, somehow the new line is not recognised.
But it is very strange because not all the time this weird symbol is shown up..
It just came up randomly. I am using ubuntu 10.04
Can anyone help me to solve this new line problem, so that it shows new line, and not weird symbol. Or maybe I can change the approach to concat the above value so that the new line is rendered correctly, and not showing a weird symbol?
The code looks ok, except for the very important fact that you are missing some headers.
strlen is in <string.h>, and malloc is in <stdlib.h>.
Include those, turn on your compiler warnings (-Wall for GCC), change your main signature to:
int main(void) { }
and actually return an int from it (or compile as C99, std=c99 for GCC), and the problems should go away.

Resources