LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   ASCII C Help, Please (https://www.linuxquestions.org/questions/programming-9/ascii-c-help-please-365467/)

InvisibleSniper 09-21-2005 12:58 AM

ASCII C Help, Please
 
Hi I have had some problem with these functions I am using to write a program that is supose to ask the user for his/her first and last name and then accept input and store it in a string array, and then print it to the screen. I can do it C++ but C is different so any help is appreciated thank you.

Code:

#include<stdio.h>


int main()
{


    char firstName[21];
    char lastName[21];
    char fullName[50];


    printf("Please enter your first name: ");
    scanf("%s", firstName);

    printf("Please enter your last name: ");
    scanf("%s", lastName);

    strcat(fullName, firstName, lastName);          //This is supose to assign both the firstName[] and lastName[] string arrays to the fullName[] string array.


    printf("%s", fullName);

    fflush(stdin);
    getchar();

}


kencaz 09-21-2005 01:13 AM

just breifly looking at it have not done c in awhile but I don't know if c recognizes the new commenting // try using the old style */ it may be having trouble interpreting the comment styles...

KC

InvisibleSniper 09-21-2005 01:23 AM

Quote:

Originally posted by kencaz
just breifly looking at it have not done c in awhile but I don't know if c recognizes the new commenting // try using the old style */ it may be having trouble interpreting the comment styles...

KC

These comments were only added in this forum for the readers to understand what that function is trying to do. But just to let you know, I have used the "//" comments in Dev-C++ compiler while writing the source code in a file that was saved as .C and it compiled and worked perfectly.

So it's not the comments but something else, I don't exactly know what but when you compile it compiles fine although the out-put is unexpected.

kencaz 09-21-2005 01:40 AM

Hmm maybe try using the string lib.

#include <string.h>

and

int main (void)

KC

paulsm4 09-21-2005 01:58 AM

Yes, you need "#include <stdio.h>" for "printf()", "scanf()", "getchar()" and friends, and "#include <string.h>" for "strcat()". But generally I'd expect these to be warnings - not fatal errors.

And I don't see anything in your source that would cause a crash.

So what exactly is the problem: is it a compile error? A runtime error? Can you cut/paste the error message?

It basically looks OK. Good job, really ;-)

InvisibleSniper 09-21-2005 01:59 AM

Quote:

Originally posted by kencaz
Hmm maybe try using the string lib.

#include <string.h>

and

int main (void)

KC

Do I just use #include<string.lib> ?

paulsm4 09-21-2005 02:07 AM

No, kenkaz misspoke himself slightly.

"string.h" is a header, not a library. You #include <string.h> before you compile your program. We're assuming that maybe you got a compile error (or warning) complaining about "strcat()", which is one of the string-related functions declared in string.h.

InvisibleSniper 09-21-2005 02:13 AM

Quote:

Originally posted by paulsm4
No, kenkaz misspoke himself slightly.

"string.h" is a header, not a library. You #include <string.h> before you compile your program. We're assuming that maybe you got a compile error (or warning) complaining about "strcat()", which is one of the string-related functions declared in string.h.

strcat(); works fine without
Code:

#include<string.h>
. I only inlude <stdio.h> for strcat to work. There was no compile error, only a runtime error. I think it has to do with how many parameters I put in strcat, which was
Code:

strcat(fullName, firstName, lastName);
I am not quite sure as to how many parameters are legal, can someone please tell me how many are legal?

Thinking 09-21-2005 02:20 AM

hiho

first do on top of your code:
#include <string.h>

and replace
strcat(fullName, firstName, lastName);
with
strcat(fullName,firstName);
strcat(fullName,lastName);

but for such things i like sprintf(); more because you can easily format your string:
sprintf(fullName,"%s %s",firstName,lastName);


just because of safety:
you have a buffer overflow problem in your prog
e.g. what if the user enters more than 21 characters for his name?
or to be more correct, if the user enters more than 42 characters you get a segmentation fault because sscanf wants to read from stdin but the buffer it want's to write in (firstName and lastName) are 42 characters in size
so sscanf would write to a buffer where it isn't allowed to

to be more safe
replace
sscanf();
with
fgets(firstName,21,stdin);
and
fgets(lastName,21,stdin);

greetz

paulsm4 09-21-2005 02:25 AM

Quote:

So what exactly is the problem: is it a compile error? A runtime error? Can you cut/paste the error message?
If you gave us the exact error, perhaps we could be of a bit more help ;-)

PS:
In most environments I know of, "strcat()" is declared in "string.h". If you try to compile a C++ program that uses "strcat()" on one of those platforms, the compile will die a fiery death. So it was a reasonable guess on our part.

And I hope you're clear about the difference between a compile-time header, a link-time library, and a runtime error. Apparently you're experiencing a runtime error. We're eager to hear exactly what that error is!

PS:
"man strcat" in a Linux environment should give you the prototype for "strcat()". It takes two arguments, not three. But I *don't* know if that would necessarily cause your crash.

PPS:
If you're on Linux, try compiling with "gcc -g ..." and running the program under the gdb debugger.

InvisibleSniper 09-21-2005 02:48 AM

The error I got, as I said was a run time error. This is basically what happened, I compiled and ran the program and typed my full name into char firstName[21]; char lastName[21]; and once I hit enter for it to display my name I got a bunch of characters that were not part of the alphabet or even part of the numerical system.

I mean it was supose to display my name. Anyway I done something similar to what Thinking said and it worked fine. But still out of interest is it so that strcat() can only take 2 parameters?

And just out of interest again, will I ever need these console functions later on in life when I'm a professional programmer?

Thinking 09-21-2005 03:24 AM

well i understand your runtime error but i don't really know what could cause the problem in your code

i didn't have this on my suse linux

as you said you get some crazy numbers and characters after you entered the lastName
this means that your printf(); does something strange
it's caused because you overwrote the ending binary 0 from the fullName string
so printf(); didn't know where the end of the string is and it printed what was in memory after the fullName string

maybe it would work if you initialize your arrays:
char firstName[21]={0};
char lastName[21]={0};
char fullName[50]={0};

btw: yes, strcat only takes 2 arguments
it concatenates the 2 strings
char *strcat(char *dest, const char *src);

if you have "hello" in buffer dest and " world" in src
then after strcat you have "hello world" in dest! and it returns dest

and for your second question:
hmm
good question
i would say yes
BUT
if you get better you can solve problems that are more complex than what you prog now
so yes, i think you will use them in future too, but in future there will be no problem for you to use them!
it will be as simple as to pick one's nose *g*

greetz

bigearsbilly 09-21-2005 03:38 AM

why use such puny buffers?
char [21] ???

how many million bytes have you got spare on your computer?
give yourself some rooooom.
;)

JCipriani 09-21-2005 03:48 AM

Looks to me like your problem is here:
Code:

strcat(fullName, firstName, lastName);
Firstly it doesn't take three parameters, but even if you did this:
Code:

strcat(fullName, firstName);
strcat(fullName, lastName);

It still wouldn't work and would most likely print garbage like the stuff you are seeing. The reason is simple: In memory, "strings" are stored as arrays of characters with the final character in the string being followed by the character 0 (that's 0, as in null, not as in the letter "O" or the digit "0").

The strcat() function concatenates the second string onto the end of the first string, and it works by finding the terminating 0 character in the first string and then copying the second string to that location. But you did not initialize the data in fullName to anything before passing it to strcat(); so whatever garbage was in memory in the location that fullName happens to be in is what's there when you call strcat() on it, and there is most likely a lot of junk before the first random 0 occurs.

You'd need to do something like this:

Code:

fullName[0] = 0;
strcat(fullName, firstName);
strcat(fullName, lastName);

That sets the first character of fullName to 0, which effectively initializes it to an empty string. Then you can safely call strcat().

Your buffers are small, but that is not the source of your problem assuming you are typing less than 20 characters in for your first and last names. Not many people have a first or last name longer than 20 characters so anything larger would probably be overkill.

Additionally, if you want to play it safe, you can prevent overruns with scanf like this (once again, this is probably not the source of your original problem, but it's just if you're curious):
Code:

char somebuf[21];

scanf("%21s", somebuf);
somebuf[20] = 0;

I can't remember if scanf writes the 0 at the end if it reaches the limit or not; forcing the last byte to be 0 is always a safe bet.

Jason

bigearsbilly 09-21-2005 03:51 AM

you haven't initialised your char buffers.

Code:

char firstName[21];
char lastName[21];
char fullName[50];

So they have old random data in them.
so when strcat comes along it cats stuff onto the random data.

I would put them outside the main, then they will be static buffers and intialised to zero.
Usually best to put buffers in static data rather than stack data as they are generally
larger storage areas.

and give them size, man.

Code:

#include<stdio.h>
#include<string.h>


#define BUFSZ 1024

char firstName[BUFSZ];
char lastName[BUFSZ];
char fullName[2 * BUFSZ];



int main()
{


    printf("Please enter your first name: ");
    scanf("%s", firstName);

    printf("Please enter your last name: ");
    scanf("%s", lastName);

    strcat(fullName, firstName, lastName);          //This is supose to assign both the firstName[] and lastName[] string arrays to the fullName[] string array.


    printf("%s", fullName);

    fflush(stdin);
    getchar();

}


bigearsbilly 09-21-2005 04:05 AM

oooops! didn't test ;)

strcat changed:


Code:

#include<stdio.h>

 char firstName[512];
  char lastName[512];
  char fullName[1024];

int main()
{


 

    printf("Please enter your first name: ");
    scanf("%s", firstName);

    printf("Please enter your last name: ");
    scanf("%s", lastName);

    sprintf(fullName, "%s %s", firstName, lastName);          //This is supose to assign both the firstName[] and lastName[] string arrays to the fullName[] string array.


    printf("%s\n", fullName);


    getchar();

}


Thinking 09-21-2005 04:29 AM

hmm

just a little question
what does fflush(stdin); ??
fflush flushes an output buffer
but stdin is input
so it should just do nothing, not?

bigearsbilly 09-21-2005 05:01 AM

'tis removed.
good spot.
(cut and pasted)

InvisibleSniper 09-21-2005 06:06 AM

I know that when you want to put a value into a variable using scanf you need to use the & operator like:
Code:

scanf("%d", &age);
. What other data types do you need to use the & operator for when using the scanf function?

Also do I need to use the & operator for arrays when accepting string input using scanf?

bigearsbilly 09-21-2005 06:14 AM

for an array don't need the &
the name is the address.

e.g:
char buffer[100];

buffer same as &buffer[0]

InvisibleSniper 09-21-2005 06:43 AM

Quote:

Originally posted by bigearsbilly
for an array don't need the &
the name is the address.

e.g:
char buffer[100];

buffer same as &buffer[0]

So I would need the & for char, float, int and double and that's all?

I know that the & symbol before a variable like:
Code:

&myAge;
is a symbol that is reffered to as the "Address Of Operator", which is used for pointers as I have learnt this from C++. Anything I need to know about this in C or is that all?

Thank Yous For You Time :)

bigearsbilly 09-21-2005 07:30 AM

correct.

trying getting familiar with a debugger.
'gdb' with 'ddd' is particularly good. you can play about and see
what's really happening in there. It all helps gain an understanding.
you can even call functions etc.

InvisibleSniper 09-22-2005 12:29 AM

Have another question. What I am trying to do with the below program is to not print any of the array on the last string literal, but still have the %4s in the string.:


Code:

/*
*Trying to work out how I would print the %s, in a string. I know in C++ it will
* print if you just put it in single quotes, for example '%s'.
*
*/
#include<stdio.h>


int main()
{
    char myFirstName[15];

    printf("Please enter your name: ");

    scanf("%s", myFirstName);

    printf("\nYour first name is %s\n", myFirstName);
    printf("How do get this to print and not the array? >> '%4s' ");


    fflush(stdin);
    getchar();



}


paulsm4 09-22-2005 12:33 AM

printf("How do get this to print and not the array? >> '%%4s' ");

PS:
Leaving out the "#include <string.h>" (from the earlier version, when you had "strcat()") and failing to return a value from "main()" (still in the current version) are both arguably bugs. At best, they're poor form.

The "fflush()" is harmless, but unnecessary. The C library automatically flushes any output pending on "stdout" before accepting input from "stdin". The third stream, "stderr", is always unbuffered and, consequently, never needs to be flushed.

As a previous poster suggested, the debugger (e.g. "gdb") can be your friend. On gcc, debugging support is enabled via the "-g" compiler switch.

Another good practice is to always compile with "full warnings". On gcc, this is the "-Wall" switch (actually, there are also other, even stricter switches you could add).

Here's what I got compiling your program with "-g" and "-Wall":
Quote:

cc -g -Wall xx.c
xx.c: In function `main':
xx.c:18: warning: too few arguments for format
xx.c:26: warning: control reaches end of non-void function

Wim Sturkenboom 09-22-2005 01:12 AM

Code:

printf("How do get this to print and not the array? >> '%4s' ");
%4s indicates that there's a parameter to print.
e.g
Code:

printf("How do get this to print and not the array? >> '%4s' ","bye bye");
// or from your code
printf("\nYour first name is %s\n", myFirstName);


Thinking 09-22-2005 02:08 AM

i think InivisbleSniper wanted to know this:
printf("How do get this to print and not the array? >> '\%4s' ");


in C you have to use a backslash for the %
if you do
printf("\%"); it will print the %
printf("\\"); will print a \
and so on ....

if you aren't sure ask yourself this question:
if i want to print
%4s
how does the printf function know if i want to print %4s or a string?
it's the backslash who makes the difference *g*

bigearsbilly 09-22-2005 03:30 AM

this?

Code:

int main(void)
{

    printf("%%4s\n");

}



$ 1
%4s
$


InvisibleSniper 09-26-2005 12:22 AM

Can someone please tell me where I can learn more of the "Standard ANSI C Functions". Something that is more informitive, has more discription then other tutorials?

chrism01 09-26-2005 12:57 AM

here's a very good C book, includes ASCII to decimal conv table and lists+definitions of std includes eg stdio.h, strcat() etc.

InvisibleSniper 09-26-2005 02:01 AM

Quote:

Originally posted by chrism01
here's a very good C book, includes ASCII to decimal conv table and lists+definitions of std includes eg stdio.h, strcat() etc.
Where's the book??

Also I was wondering how do I accept user input for a "char". I mean accept user input for just one character no more and no less. I have a program that is not working because of this. It gets up to the part where the user is supose to enter a S for single or a D for double. But then it crashes, if someone could tell me how to fix this program without including any new functions that I don't know about yet, that would be very helpful.

Code:

#include<stdio.h>


int main()

{

/*This program is supose to get the title, artist, number of tracks, price and if the CD is a single or double. The program gets up to single or double and crashes./*


    char title[41] = " ";
    char artist[41] = " ";
    int numOfTracks = 0;
    float price = 0;
    char albumSinDou = " ";

    printf("Please enter the title of the CD: ");
    scanf("%[^\n]", title);
    fflush(stdin);

    printf("\nPlease enter the artist of the CD: ");
    scanf("%[^\n]", artist);


    printf("\nPlease enter the number of tracks the CD has: ");
    scanf("%d", &numOfTracks);

    printf("\nPlease enter the price of the CD: ");
    scanf("%f", &price);

    printf("\nIs this CD a single or double, please press s for single or d for double: ");
    scanf("%c", albumSinDou);

    printf("Title: %s, Artist: %s, Tracks: %d, Price: $%.2f, %c", title, artist, numOfTracks, price, albumSinDou);
    fflush(stdin);
    getchar();





}

I would only like one charachter to be accepted into the single or double variable this is why I did not make it an array.


Thank You.

Lux Perpetua 09-26-2005 03:19 AM

When scanf-ing into a numeric type like char, remember to put "&" in front of the variable. Otherwise, you will have a serious bug (that most compilers will never catch!). Also, you can't really say char c = " " because " " is a string, not a character. Maybe you meant ' '. Your compiler should at least have warned you about that.

InvisibleSniper 09-26-2005 03:23 AM

Thanks, I fixed it up now :)

cheers

InvisibleSniper 10-10-2005 10:19 AM

Sorry for the double post but this thread was more appropriate then opening an entirely new one.
  • Ok, I wanted to know does anyone know of any good books or user-friendly references to the ANSI functions within the C programming language?
  • And also can anyone put me on the right track regarding how to go about making a useful, more sophisticated program. I know a fair bit of C now, but I do not know where to start in making a program.

bigearsbilly 10-10-2005 10:25 AM

Kernighan and Ritchie.
C programming language

I usually use the man pages.


All times are GMT -5. The time now is 08:17 PM.