Entering strings into a array


4 replies [Last post]
Whatwhat
Whatwhat's picture
Offline
Joined: 2012-07-19
Points: 0

I would like to work on a project that allows me to enter a string of 12 char into an array. I've done the char user input part to scanf. Since I don't know how many entries will be made I think I need to incorporate calloc or malloc, but can't seem to find examples I can deconstruct to create program. Thanks for the help.   

 

 

#include <stdio.h>

 

int main(int argc, char *argv[]) {

 

char CAM [13];

 

printf ("Enter CAM?");

scanf("%s", CAM);

printf("\n CAM entered \n");

 

printf("%s", CAM);

 

return (0);

}

 

 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Alder
Alder's picture
Offline
Joined: 2012-07-19
Points: 0

Are you trying to make an array of strings, where each string (CAM) is an array of 12 characters?  In other words:

CAMArray[0] ---> "123456789abc"

CAMArray[1] ---> "0987654321zy"

...etc.

If that's what you're wanting to do, you'll want to use a char**.  If you want to hard-code it without worrying about memory allocation, you could do char[][] and define a const int for the max size.  For example: http://paste.ubuntu.com/1154516/

That might not be safe, though, and assumes a lot about the input.  I dunno.  By the way, return is not a function, so you don't need to put the parenthesis ((0)) after it.  "return 0" is fine.  Hope that helps somewhat.  

 

masroor342
masroor342's picture
Offline
I've been here since the first tree. I am beta
Joined: 2012-02-09
Points: 0

i think you should use if statement to check how many characters are entered if more or less then 13 return false  or this might be helpful for you http://www.cplusplus.com/reference/clibrary/cstring/strlen/

Whatwhat
Whatwhat's picture
Offline
Joined: 2012-07-19
Points: 0

Alder thanks for the reply.

Thanks for the help with putting the code together. Now that I see the direction I should be heading. I was able to modify the code to create a second break sequence that next goes into a search function of first array and places new cam strings into a second CAMArray2. After getting through the coding errors (3hours) I realized the strcmp function wasn't the correct thing to use. I seemed to only get exact matches when I entered the string in the same order as I originally entered int the  CAMArray input. I need to learn more about the qsort function. 

 

I've read alot of your posts. How long have you been working with C?

Alder
Alder's picture
Offline
Joined: 2012-07-19
Points: 0

Whatwhat wrote:

I've read alot of your posts. How long have you been working with C?

 

I started learning it on Wibit about a month ago.  Before that, I had a C book "C in 24 hours" that I partially went through.  But I have a year of C++ and a few years of C#/Java under my belt.  I'm still getting used to memory management :P