I've been working on this assignment for two days now and I'm stumped.
My first issue: I thought maybe there was something in C that could read full sentences from stdin, i browsed forums and found some suggestions such as:
Code:
scanf("%100[^\n]s", string);
but that's not working for me. so i came up with my own function and its not giving me the results i want. here is the function including the call from main:
Code:
/* * * * * * * * * * * * * *
* FROM MAIN *
* * * * * * * * * * * * * */
printf("\nAdding a new part...\n\t");
printf("Enter part name: ");
get_string(new_part.pname);
/* * * * * * * * * * * * * * * * * * *
* FUNCTION DEFINITION *
* * * * * * * * * * * * * * * * * * * /
void get_string(char *string)
{
int length = 0;
char string_cat[25];
fpurge(stdin);
while(string_cat[length] < 25)
{
if (string_cat[length] != '\n')
{
scanf("%s", string_cat);
strcat(string, string_cat);
length = strlen(string) -1;
}
}
string[length + 1] = '\0';
fpurge(stdin);
}
/* * * * * * * * * * *
* INPUT *
* * * * * * * * * * */
new part
/* * * * * * * * * * * * * * * * * * * * * * *
* UNDESIRED OUTPUT *
* * * * * * * * * * * * * * * * * * * * * * */
8newpart
where is the eight coming from? i thought fpurge clear the buffer. Also, I'm trying to add spaces in between words... i thought maybe putting within the while loop but outside of the if statement string[length +1] = '\0' would work, but it doesn't. so i put it outside of the loop but that i knew that wouldnt work either.
Problem #2 is reading from a file.. so far i have the following code which reads everything perfectly except the .txt file has a new line character at the end and i think its reading it:
Code:
/* * * * * * * * * * * * * * * * *
* READS FROM FILE *
* * * * * * * * * * * * * * * * */
if(read_in != NULL)
{
while ((fgets(read_string, MAX_PARTS ,read_in) != NULL) && (array_position < MAX_PARTS))
{
sscanf(read_string, "%17c %s %lf %s %s %d", parts.elements[array_position].pname, parts.elements[array_position].pnumber, &parts.elements[array_position].weight, parts.elements[array_position].supplier1, parts.elements[array_position].supplier2, &parts.elements[array_position].in_stock);
remove_spaces(parts.elements[array_position].pname);
array_position++;
parts.last++;
}
}
fclose(read_in);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* PLEASE HELP ME REMOVE THE LAST LINE OF JUNK *
* this is what it reads when i test it *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
ball bearings 1212-03, 3.7800000 N, 830 in stock
, 0.0000000 N, 0 in stock
i want it to stop after reading the ball bearings line. a lot of issues for one post, but all related to reading inputs so i put it all on one. can someone please help me?