How JustAnswer Works:
  • Ask an Expert
    Experts are full of valuable knowledge and are ready to help with any question. Credentials confirmed by a Fortune 500 verification firm.
  • Get a Professional Answer
    Via email, text message, or notification as you wait on our site. Ask follow up questions if you need to.
  • 100% Satisfaction Guarantee
    Rate the answer you receive.
Ask Ingo U Your Own Question
Ingo U
Ingo U, Software Engineer
Category: Programming
Satisfied Customers: 755
Experience:  Over 25 years experience in software development. Expert in Microsoft .Net, C#, C++, VB, SQL
44076068
Type Your Programming Question Here...
Ingo U is online now

, I've got some code here in C, the linked list, and I

Resolved Question:

Hello, I've got some code here in C, the linked list, and I would like the program to break out of a while loop when the string "exit" is entered:
#include
#include
#include
struct Node {
char *str;
struct Node *next;
};
int main() {
int res;
char text[80];
struct Node *root;
struct Node *trav;
root = (struct Node*)malloc(sizeof(struct Node));
printf("Enter string: ");
scanf("%s", &text);
printf("\n");
root -> str = (char *)malloc(strlen(text) + 1);
strcpy(root -> str, text);
trav = root;
while(1) {
trav -> next = (struct Node*)malloc(sizeof(struct Node));
trav = trav -> next;
printf("Enter string: ");
scanf("%s", &text);
printf("\n");
res = strcmp(text, "exit");
if(res == 0)
break;
trav -> str = (char *)malloc(strlen(text) + 1);
strcpy(trav -> str, text);
}
trav -> str = 0;
trav = root;
while(trav != 0) {
printf("%s ", trav -> str);
trav = trav -> next;
}
printf("\n");
return 0;
}
Submitted: 2 years ago.
Category: Programming
Expert:  Ingo U replied 2 years ago.
Hello again,
I'll post an update to the previous code to do this, soon, OK?
Customer: replied 2 years ago.

That's fine. Thank you.

Expert:  Ingo U replied 2 years ago.
Well I loaded and stepped through the code, and it does break out of the loop when you type exit, you had the right idea about using strcmp().
But your linked list ends up with a badly "formed" node at the end. Is it your intent in the end to have a list exactly of the number of node for which the user entered data (excluding the "exit" word of course) ?
I would restructure the loops a little to do that, if it's OK with you.
Customer: replied 2 years ago.

I like to keep entering data for storage in a node (like an array) and then when 'exit' is entered, break out of the loop without storing the word 'exit'.

Expert:  Ingo U replied 2 years ago.
OK, here's the new code:
https://www.dropbox.com/s/7ywfaobkf5kbt7e/LinkedList.c?dl=0
I hope what I did makes sense to you.
Regards,
Ingo
Ingo U and other Programming Specialists are ready to help you