Scanf keeps waiting for input after a string with spaces is entered?












0















This is the function that captures the string:



void capture(char string) {
printf("_____________________________________________________________nn");
printf("Ingrese una cadena: ");
scanf(" %[^n]s", string);
printf("Cadena capturada: %sn", string);
printf("_____________________________________________________________nn");
}


This is the function that is being called in the main function:



    void sort(char string) {  
int opt, i, j, temp = 0;
char string_copy[50];
strcpy(string_copy, string);
for (i = 0; string_copy[i] != ''; i++)
for (i = 0; string_copy[i] != ''; i++) {
for (j = i + 1; string_copy[j] != ''; j++) {
if (string_copy[i] > string_copy[j]) {
temp = string_copy[i];
string_copy[i] = string_copy[j];
string_copy[j] = temp;
}
}
}

printf("_____________________________________________________________nn");
printf("Ordenar de modo:n1) Ascendenten2) Descendenten");
printf("Seleccione una opcion: ");
fflush(stdin);
scanf(" %d", &opt);
switch(opt) {
case 1:
printf("'%s' ordenado de forma ascendente: %sn", string, string_copy);
break;
case 2:
printf("'%s' ordenado de forma descendente: ", string);
for (i=strlen(string); i != 0; i--)
printf("%c", string_copy[i]);
printf("n");
break;
default: printf("[ ! ] Selección incorrecta!n"); break;
}
printf("_____________________________________________________________nn");
}

//Imprimir la última palabra de la cadena
void last_word(char string[50]) {
printf("_____________________________________________________________nn");
int i, count = 0;
for (i=0; string[i] != ''; i++) {
if (string[i] == ' ') {
count = i;
}
}
if (count == 0) {
printf("Solamente hay una palabra: %sn", string);
} else {
printf("La última palabra en '%s' es: ", string);
for (i=count; string[i] != ''; i++) {
printf("%c", string[i]);
}
printf("n");
}
printf("_____________________________________________________________nn");
}


And this is the code that has the problem:



int main() {
int opc = 0;
char string[50];
do {
printf("MENU:n");
printf("1) Capturar cadenan");
printf("2) Sustituir un caracter por otron");
printf("3) Buscar un caracter e imprimir el número de veces que aparecen");
printf("4) Buscar un caracter para eliminar de la cadena.n");
printf("5) Ordenar los caracteres alfabéticamenten");
printf("6) Imprimir la última palabra de la cadenan");
printf("0) Salirn");
printf("Seleccione una opcion: ");
scanf("%i", &opc);
printf("Opcion: %d", opc);
switch(opc) {
case 1:{
capture(string);
break;
}
case 2:{
replace(string);
break;
}
case 3:{
num_char(string);
break;
}
case 4:{
delete(string);
break;
}
case 5:{
sort(string);
break;
}
case 6:{
last_word(string);
break;
}
case 0:{
printf("Byen");
break;
}
default: {
printf("[ ! ] Selección incorrecta!n");
}
}
} while (opc != 0);

return 0;
}


The problem is with option five above in the switch case: It only executes if the captured string does not have any spaces. If you would input "Hello world" for example. Case 5 will never execute and the scanf



printf("Seleccione una opcion: ");
scanf("%i", &opc);


Will just stay there waiting for an input. This only happens, I repeat, if the string captured has spaces AND you choose option five in the switch case.










share|improve this question

























  • I wonder if there is some error or endless loop in the function sort...

    – Geno Chen
    Nov 25 '18 at 19:51











  • @GenoChen Added the sort function to the original post.

    – Uriel Guzmán
    Nov 25 '18 at 19:54











  • @DavidSchwartz Because if I don't, Visual Basic gives me the error 'Segmentation fault (core dumped)' :(

    – Uriel Guzmán
    Nov 25 '18 at 19:56











  • @UrielGuzmán If you made changes you don't understand to fix bugs, you should take them out before you ask for help and post the code that you think should work. Otherwise, the help you get may leave you back where you were in the first place and, worse, it's advice about code you didn't understand and wouldn't have written. (Likely the answer I gave you just puts you back where you were before you broke your code more trying to fix it. Sorry.)

    – David Schwartz
    Nov 25 '18 at 19:57













  • @DavidSchwartz Thanks. I fixed the array problems in the original post. But the problem is still occurring.

    – Uriel Guzmán
    Nov 25 '18 at 20:14
















0















This is the function that captures the string:



void capture(char string) {
printf("_____________________________________________________________nn");
printf("Ingrese una cadena: ");
scanf(" %[^n]s", string);
printf("Cadena capturada: %sn", string);
printf("_____________________________________________________________nn");
}


This is the function that is being called in the main function:



    void sort(char string) {  
int opt, i, j, temp = 0;
char string_copy[50];
strcpy(string_copy, string);
for (i = 0; string_copy[i] != ''; i++)
for (i = 0; string_copy[i] != ''; i++) {
for (j = i + 1; string_copy[j] != ''; j++) {
if (string_copy[i] > string_copy[j]) {
temp = string_copy[i];
string_copy[i] = string_copy[j];
string_copy[j] = temp;
}
}
}

printf("_____________________________________________________________nn");
printf("Ordenar de modo:n1) Ascendenten2) Descendenten");
printf("Seleccione una opcion: ");
fflush(stdin);
scanf(" %d", &opt);
switch(opt) {
case 1:
printf("'%s' ordenado de forma ascendente: %sn", string, string_copy);
break;
case 2:
printf("'%s' ordenado de forma descendente: ", string);
for (i=strlen(string); i != 0; i--)
printf("%c", string_copy[i]);
printf("n");
break;
default: printf("[ ! ] Selección incorrecta!n"); break;
}
printf("_____________________________________________________________nn");
}

//Imprimir la última palabra de la cadena
void last_word(char string[50]) {
printf("_____________________________________________________________nn");
int i, count = 0;
for (i=0; string[i] != ''; i++) {
if (string[i] == ' ') {
count = i;
}
}
if (count == 0) {
printf("Solamente hay una palabra: %sn", string);
} else {
printf("La última palabra en '%s' es: ", string);
for (i=count; string[i] != ''; i++) {
printf("%c", string[i]);
}
printf("n");
}
printf("_____________________________________________________________nn");
}


And this is the code that has the problem:



int main() {
int opc = 0;
char string[50];
do {
printf("MENU:n");
printf("1) Capturar cadenan");
printf("2) Sustituir un caracter por otron");
printf("3) Buscar un caracter e imprimir el número de veces que aparecen");
printf("4) Buscar un caracter para eliminar de la cadena.n");
printf("5) Ordenar los caracteres alfabéticamenten");
printf("6) Imprimir la última palabra de la cadenan");
printf("0) Salirn");
printf("Seleccione una opcion: ");
scanf("%i", &opc);
printf("Opcion: %d", opc);
switch(opc) {
case 1:{
capture(string);
break;
}
case 2:{
replace(string);
break;
}
case 3:{
num_char(string);
break;
}
case 4:{
delete(string);
break;
}
case 5:{
sort(string);
break;
}
case 6:{
last_word(string);
break;
}
case 0:{
printf("Byen");
break;
}
default: {
printf("[ ! ] Selección incorrecta!n");
}
}
} while (opc != 0);

return 0;
}


The problem is with option five above in the switch case: It only executes if the captured string does not have any spaces. If you would input "Hello world" for example. Case 5 will never execute and the scanf



printf("Seleccione una opcion: ");
scanf("%i", &opc);


Will just stay there waiting for an input. This only happens, I repeat, if the string captured has spaces AND you choose option five in the switch case.










share|improve this question

























  • I wonder if there is some error or endless loop in the function sort...

    – Geno Chen
    Nov 25 '18 at 19:51











  • @GenoChen Added the sort function to the original post.

    – Uriel Guzmán
    Nov 25 '18 at 19:54











  • @DavidSchwartz Because if I don't, Visual Basic gives me the error 'Segmentation fault (core dumped)' :(

    – Uriel Guzmán
    Nov 25 '18 at 19:56











  • @UrielGuzmán If you made changes you don't understand to fix bugs, you should take them out before you ask for help and post the code that you think should work. Otherwise, the help you get may leave you back where you were in the first place and, worse, it's advice about code you didn't understand and wouldn't have written. (Likely the answer I gave you just puts you back where you were before you broke your code more trying to fix it. Sorry.)

    – David Schwartz
    Nov 25 '18 at 19:57













  • @DavidSchwartz Thanks. I fixed the array problems in the original post. But the problem is still occurring.

    – Uriel Guzmán
    Nov 25 '18 at 20:14














0












0








0








This is the function that captures the string:



void capture(char string) {
printf("_____________________________________________________________nn");
printf("Ingrese una cadena: ");
scanf(" %[^n]s", string);
printf("Cadena capturada: %sn", string);
printf("_____________________________________________________________nn");
}


This is the function that is being called in the main function:



    void sort(char string) {  
int opt, i, j, temp = 0;
char string_copy[50];
strcpy(string_copy, string);
for (i = 0; string_copy[i] != ''; i++)
for (i = 0; string_copy[i] != ''; i++) {
for (j = i + 1; string_copy[j] != ''; j++) {
if (string_copy[i] > string_copy[j]) {
temp = string_copy[i];
string_copy[i] = string_copy[j];
string_copy[j] = temp;
}
}
}

printf("_____________________________________________________________nn");
printf("Ordenar de modo:n1) Ascendenten2) Descendenten");
printf("Seleccione una opcion: ");
fflush(stdin);
scanf(" %d", &opt);
switch(opt) {
case 1:
printf("'%s' ordenado de forma ascendente: %sn", string, string_copy);
break;
case 2:
printf("'%s' ordenado de forma descendente: ", string);
for (i=strlen(string); i != 0; i--)
printf("%c", string_copy[i]);
printf("n");
break;
default: printf("[ ! ] Selección incorrecta!n"); break;
}
printf("_____________________________________________________________nn");
}

//Imprimir la última palabra de la cadena
void last_word(char string[50]) {
printf("_____________________________________________________________nn");
int i, count = 0;
for (i=0; string[i] != ''; i++) {
if (string[i] == ' ') {
count = i;
}
}
if (count == 0) {
printf("Solamente hay una palabra: %sn", string);
} else {
printf("La última palabra en '%s' es: ", string);
for (i=count; string[i] != ''; i++) {
printf("%c", string[i]);
}
printf("n");
}
printf("_____________________________________________________________nn");
}


And this is the code that has the problem:



int main() {
int opc = 0;
char string[50];
do {
printf("MENU:n");
printf("1) Capturar cadenan");
printf("2) Sustituir un caracter por otron");
printf("3) Buscar un caracter e imprimir el número de veces que aparecen");
printf("4) Buscar un caracter para eliminar de la cadena.n");
printf("5) Ordenar los caracteres alfabéticamenten");
printf("6) Imprimir la última palabra de la cadenan");
printf("0) Salirn");
printf("Seleccione una opcion: ");
scanf("%i", &opc);
printf("Opcion: %d", opc);
switch(opc) {
case 1:{
capture(string);
break;
}
case 2:{
replace(string);
break;
}
case 3:{
num_char(string);
break;
}
case 4:{
delete(string);
break;
}
case 5:{
sort(string);
break;
}
case 6:{
last_word(string);
break;
}
case 0:{
printf("Byen");
break;
}
default: {
printf("[ ! ] Selección incorrecta!n");
}
}
} while (opc != 0);

return 0;
}


The problem is with option five above in the switch case: It only executes if the captured string does not have any spaces. If you would input "Hello world" for example. Case 5 will never execute and the scanf



printf("Seleccione una opcion: ");
scanf("%i", &opc);


Will just stay there waiting for an input. This only happens, I repeat, if the string captured has spaces AND you choose option five in the switch case.










share|improve this question
















This is the function that captures the string:



void capture(char string) {
printf("_____________________________________________________________nn");
printf("Ingrese una cadena: ");
scanf(" %[^n]s", string);
printf("Cadena capturada: %sn", string);
printf("_____________________________________________________________nn");
}


This is the function that is being called in the main function:



    void sort(char string) {  
int opt, i, j, temp = 0;
char string_copy[50];
strcpy(string_copy, string);
for (i = 0; string_copy[i] != ''; i++)
for (i = 0; string_copy[i] != ''; i++) {
for (j = i + 1; string_copy[j] != ''; j++) {
if (string_copy[i] > string_copy[j]) {
temp = string_copy[i];
string_copy[i] = string_copy[j];
string_copy[j] = temp;
}
}
}

printf("_____________________________________________________________nn");
printf("Ordenar de modo:n1) Ascendenten2) Descendenten");
printf("Seleccione una opcion: ");
fflush(stdin);
scanf(" %d", &opt);
switch(opt) {
case 1:
printf("'%s' ordenado de forma ascendente: %sn", string, string_copy);
break;
case 2:
printf("'%s' ordenado de forma descendente: ", string);
for (i=strlen(string); i != 0; i--)
printf("%c", string_copy[i]);
printf("n");
break;
default: printf("[ ! ] Selección incorrecta!n"); break;
}
printf("_____________________________________________________________nn");
}

//Imprimir la última palabra de la cadena
void last_word(char string[50]) {
printf("_____________________________________________________________nn");
int i, count = 0;
for (i=0; string[i] != ''; i++) {
if (string[i] == ' ') {
count = i;
}
}
if (count == 0) {
printf("Solamente hay una palabra: %sn", string);
} else {
printf("La última palabra en '%s' es: ", string);
for (i=count; string[i] != ''; i++) {
printf("%c", string[i]);
}
printf("n");
}
printf("_____________________________________________________________nn");
}


And this is the code that has the problem:



int main() {
int opc = 0;
char string[50];
do {
printf("MENU:n");
printf("1) Capturar cadenan");
printf("2) Sustituir un caracter por otron");
printf("3) Buscar un caracter e imprimir el número de veces que aparecen");
printf("4) Buscar un caracter para eliminar de la cadena.n");
printf("5) Ordenar los caracteres alfabéticamenten");
printf("6) Imprimir la última palabra de la cadenan");
printf("0) Salirn");
printf("Seleccione una opcion: ");
scanf("%i", &opc);
printf("Opcion: %d", opc);
switch(opc) {
case 1:{
capture(string);
break;
}
case 2:{
replace(string);
break;
}
case 3:{
num_char(string);
break;
}
case 4:{
delete(string);
break;
}
case 5:{
sort(string);
break;
}
case 6:{
last_word(string);
break;
}
case 0:{
printf("Byen");
break;
}
default: {
printf("[ ! ] Selección incorrecta!n");
}
}
} while (opc != 0);

return 0;
}


The problem is with option five above in the switch case: It only executes if the captured string does not have any spaces. If you would input "Hello world" for example. Case 5 will never execute and the scanf



printf("Seleccione una opcion: ");
scanf("%i", &opc);


Will just stay there waiting for an input. This only happens, I repeat, if the string captured has spaces AND you choose option five in the switch case.







string input scanf spaces






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 20:11







Uriel Guzmán

















asked Nov 25 '18 at 19:47









Uriel GuzmánUriel Guzmán

11




11













  • I wonder if there is some error or endless loop in the function sort...

    – Geno Chen
    Nov 25 '18 at 19:51











  • @GenoChen Added the sort function to the original post.

    – Uriel Guzmán
    Nov 25 '18 at 19:54











  • @DavidSchwartz Because if I don't, Visual Basic gives me the error 'Segmentation fault (core dumped)' :(

    – Uriel Guzmán
    Nov 25 '18 at 19:56











  • @UrielGuzmán If you made changes you don't understand to fix bugs, you should take them out before you ask for help and post the code that you think should work. Otherwise, the help you get may leave you back where you were in the first place and, worse, it's advice about code you didn't understand and wouldn't have written. (Likely the answer I gave you just puts you back where you were before you broke your code more trying to fix it. Sorry.)

    – David Schwartz
    Nov 25 '18 at 19:57













  • @DavidSchwartz Thanks. I fixed the array problems in the original post. But the problem is still occurring.

    – Uriel Guzmán
    Nov 25 '18 at 20:14



















  • I wonder if there is some error or endless loop in the function sort...

    – Geno Chen
    Nov 25 '18 at 19:51











  • @GenoChen Added the sort function to the original post.

    – Uriel Guzmán
    Nov 25 '18 at 19:54











  • @DavidSchwartz Because if I don't, Visual Basic gives me the error 'Segmentation fault (core dumped)' :(

    – Uriel Guzmán
    Nov 25 '18 at 19:56











  • @UrielGuzmán If you made changes you don't understand to fix bugs, you should take them out before you ask for help and post the code that you think should work. Otherwise, the help you get may leave you back where you were in the first place and, worse, it's advice about code you didn't understand and wouldn't have written. (Likely the answer I gave you just puts you back where you were before you broke your code more trying to fix it. Sorry.)

    – David Schwartz
    Nov 25 '18 at 19:57













  • @DavidSchwartz Thanks. I fixed the array problems in the original post. But the problem is still occurring.

    – Uriel Guzmán
    Nov 25 '18 at 20:14

















I wonder if there is some error or endless loop in the function sort...

– Geno Chen
Nov 25 '18 at 19:51





I wonder if there is some error or endless loop in the function sort...

– Geno Chen
Nov 25 '18 at 19:51













@GenoChen Added the sort function to the original post.

– Uriel Guzmán
Nov 25 '18 at 19:54





@GenoChen Added the sort function to the original post.

– Uriel Guzmán
Nov 25 '18 at 19:54













@DavidSchwartz Because if I don't, Visual Basic gives me the error 'Segmentation fault (core dumped)' :(

– Uriel Guzmán
Nov 25 '18 at 19:56





@DavidSchwartz Because if I don't, Visual Basic gives me the error 'Segmentation fault (core dumped)' :(

– Uriel Guzmán
Nov 25 '18 at 19:56













@UrielGuzmán If you made changes you don't understand to fix bugs, you should take them out before you ask for help and post the code that you think should work. Otherwise, the help you get may leave you back where you were in the first place and, worse, it's advice about code you didn't understand and wouldn't have written. (Likely the answer I gave you just puts you back where you were before you broke your code more trying to fix it. Sorry.)

– David Schwartz
Nov 25 '18 at 19:57







@UrielGuzmán If you made changes you don't understand to fix bugs, you should take them out before you ask for help and post the code that you think should work. Otherwise, the help you get may leave you back where you were in the first place and, worse, it's advice about code you didn't understand and wouldn't have written. (Likely the answer I gave you just puts you back where you were before you broke your code more trying to fix it. Sorry.)

– David Schwartz
Nov 25 '18 at 19:57















@DavidSchwartz Thanks. I fixed the array problems in the original post. But the problem is still occurring.

– Uriel Guzmán
Nov 25 '18 at 20:14





@DavidSchwartz Thanks. I fixed the array problems in the original post. But the problem is still occurring.

– Uriel Guzmán
Nov 25 '18 at 20:14












2 Answers
2






active

oldest

votes


















1














            capture(&string[50]);


You are passing capture the address of string[50]. But there is no string[50]. So you are passing an address past the end of string to capture. (Since string has fifty entries and 0 is the first, 49 is the last. There is no string[50], it's past the end of the array.



void capture(char string[50]) {
printf("_____________________________________________________________nn");
printf("Ingrese una cadena: ");
scanf(" %[^n]s", string);
printf("Cadena capturada: %sn", string);
printf("_____________________________________________________________nn");
}


Ooops, capture writes to the address it was past for string, but that's past the end of the array you allocated. Writing to memory outside the bounds you allocated can trample other variables and cause unpredictable results. Until you fix out of bounds writes, you really can't debug anything else in your program. You can use valgrind or a similar tool to help detect these kinds of errors.






share|improve this answer
























  • It seems I was incorrectly passing arrays to the function. Fixed that in the original post. However, the problem still remains. PS: The program crashes as it waits for the input. It looks like an infinite loop problem too.

    – Uriel Guzmán
    Nov 25 '18 at 20:08













  • You hit the core of the question. I tried gdb on my device, and found a stack smashing after return 0; of main. But I don't know why it is at this statement.

    – Geno Chen
    Nov 25 '18 at 20:12











  • Oh, for the original question's code, even string and string_copy are rewritten into some unexpected value...

    – Geno Chen
    Nov 25 '18 at 20:14



















0














I tried to understand your logic and it seems there is a problem in there:



Why are you passing string[50] to each function? I assume you would like to use the same string variable in every function, so, there's two points for you to check:




  1. You should ask for the user to enter the string value before the switch() statement - call capture() in the row before the switch() line, for example. Otherwise, the user could enter other menu options before entering the "capture" function, and, in this case the string will not exist yet, causing a segmentation error - if I'm not mistaken. (Have you tried it? Choosing option 3, for example, before choosing option 1? It must not work)


  2. To pass the "string" variable by parameter, use "string", not "string[50]".
    After the declaration (where "50" is the size of the string), the expression "string[50]" represents the 50th value of the string, which doesn't even exist, as pointed in David's answer.







share|improve this answer
























  • Yes. David was right about that one. Already corrected the string parameters in the original post a few minutes ago. (It's now passing string instead of &string[50]). The segmentation error disappeared after I corrected it, though. But the original problem of the question still remains. I also just did what you said in point 1. Allthough it didn't fix the problem. I will keep it like that because, as you said, it's better to have the string captured before anything else.

    – Uriel Guzmán
    Nov 25 '18 at 20:28













  • Have you checked issue number 1?

    – Ândrea Andrade
    Nov 25 '18 at 20:31











  • I also don't understand the line "scanf(" %[^n]s", string);" in function capture(). Have you tried using just "scanf("%50c", string)" ? %s reads any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence. From: cplusplus.com/reference/cstdio/scanf You make take a look there ...

    – Ândrea Andrade
    Nov 25 '18 at 20:31













  • Sorry, I made a typo. I meant I corrected issue 1 (and 2 too). scanf(" %[^n]s", string); is for accepting string with spaces, stopping until the newline character is encountered. I left a space at first, because the newline character of the option menu was messing with the scanf. Tried fgets() and even using getchar() to eat the newline character but they seem to have nothing to do with the original problem.

    – Uriel Guzmán
    Nov 25 '18 at 20:34













  • I see.. I'll need to leave right now, but I can try to help you later if the problem persists. I reccomended a link for you in the previous comment, hope it helps.. ': )

    – Ândrea Andrade
    Nov 25 '18 at 20:37











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471243%2fscanf-keeps-waiting-for-input-after-a-string-with-spaces-is-entered%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














            capture(&string[50]);


You are passing capture the address of string[50]. But there is no string[50]. So you are passing an address past the end of string to capture. (Since string has fifty entries and 0 is the first, 49 is the last. There is no string[50], it's past the end of the array.



void capture(char string[50]) {
printf("_____________________________________________________________nn");
printf("Ingrese una cadena: ");
scanf(" %[^n]s", string);
printf("Cadena capturada: %sn", string);
printf("_____________________________________________________________nn");
}


Ooops, capture writes to the address it was past for string, but that's past the end of the array you allocated. Writing to memory outside the bounds you allocated can trample other variables and cause unpredictable results. Until you fix out of bounds writes, you really can't debug anything else in your program. You can use valgrind or a similar tool to help detect these kinds of errors.






share|improve this answer
























  • It seems I was incorrectly passing arrays to the function. Fixed that in the original post. However, the problem still remains. PS: The program crashes as it waits for the input. It looks like an infinite loop problem too.

    – Uriel Guzmán
    Nov 25 '18 at 20:08













  • You hit the core of the question. I tried gdb on my device, and found a stack smashing after return 0; of main. But I don't know why it is at this statement.

    – Geno Chen
    Nov 25 '18 at 20:12











  • Oh, for the original question's code, even string and string_copy are rewritten into some unexpected value...

    – Geno Chen
    Nov 25 '18 at 20:14
















1














            capture(&string[50]);


You are passing capture the address of string[50]. But there is no string[50]. So you are passing an address past the end of string to capture. (Since string has fifty entries and 0 is the first, 49 is the last. There is no string[50], it's past the end of the array.



void capture(char string[50]) {
printf("_____________________________________________________________nn");
printf("Ingrese una cadena: ");
scanf(" %[^n]s", string);
printf("Cadena capturada: %sn", string);
printf("_____________________________________________________________nn");
}


Ooops, capture writes to the address it was past for string, but that's past the end of the array you allocated. Writing to memory outside the bounds you allocated can trample other variables and cause unpredictable results. Until you fix out of bounds writes, you really can't debug anything else in your program. You can use valgrind or a similar tool to help detect these kinds of errors.






share|improve this answer
























  • It seems I was incorrectly passing arrays to the function. Fixed that in the original post. However, the problem still remains. PS: The program crashes as it waits for the input. It looks like an infinite loop problem too.

    – Uriel Guzmán
    Nov 25 '18 at 20:08













  • You hit the core of the question. I tried gdb on my device, and found a stack smashing after return 0; of main. But I don't know why it is at this statement.

    – Geno Chen
    Nov 25 '18 at 20:12











  • Oh, for the original question's code, even string and string_copy are rewritten into some unexpected value...

    – Geno Chen
    Nov 25 '18 at 20:14














1












1








1







            capture(&string[50]);


You are passing capture the address of string[50]. But there is no string[50]. So you are passing an address past the end of string to capture. (Since string has fifty entries and 0 is the first, 49 is the last. There is no string[50], it's past the end of the array.



void capture(char string[50]) {
printf("_____________________________________________________________nn");
printf("Ingrese una cadena: ");
scanf(" %[^n]s", string);
printf("Cadena capturada: %sn", string);
printf("_____________________________________________________________nn");
}


Ooops, capture writes to the address it was past for string, but that's past the end of the array you allocated. Writing to memory outside the bounds you allocated can trample other variables and cause unpredictable results. Until you fix out of bounds writes, you really can't debug anything else in your program. You can use valgrind or a similar tool to help detect these kinds of errors.






share|improve this answer













            capture(&string[50]);


You are passing capture the address of string[50]. But there is no string[50]. So you are passing an address past the end of string to capture. (Since string has fifty entries and 0 is the first, 49 is the last. There is no string[50], it's past the end of the array.



void capture(char string[50]) {
printf("_____________________________________________________________nn");
printf("Ingrese una cadena: ");
scanf(" %[^n]s", string);
printf("Cadena capturada: %sn", string);
printf("_____________________________________________________________nn");
}


Ooops, capture writes to the address it was past for string, but that's past the end of the array you allocated. Writing to memory outside the bounds you allocated can trample other variables and cause unpredictable results. Until you fix out of bounds writes, you really can't debug anything else in your program. You can use valgrind or a similar tool to help detect these kinds of errors.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 25 '18 at 19:55









David SchwartzDavid Schwartz

138k14144226




138k14144226













  • It seems I was incorrectly passing arrays to the function. Fixed that in the original post. However, the problem still remains. PS: The program crashes as it waits for the input. It looks like an infinite loop problem too.

    – Uriel Guzmán
    Nov 25 '18 at 20:08













  • You hit the core of the question. I tried gdb on my device, and found a stack smashing after return 0; of main. But I don't know why it is at this statement.

    – Geno Chen
    Nov 25 '18 at 20:12











  • Oh, for the original question's code, even string and string_copy are rewritten into some unexpected value...

    – Geno Chen
    Nov 25 '18 at 20:14



















  • It seems I was incorrectly passing arrays to the function. Fixed that in the original post. However, the problem still remains. PS: The program crashes as it waits for the input. It looks like an infinite loop problem too.

    – Uriel Guzmán
    Nov 25 '18 at 20:08













  • You hit the core of the question. I tried gdb on my device, and found a stack smashing after return 0; of main. But I don't know why it is at this statement.

    – Geno Chen
    Nov 25 '18 at 20:12











  • Oh, for the original question's code, even string and string_copy are rewritten into some unexpected value...

    – Geno Chen
    Nov 25 '18 at 20:14

















It seems I was incorrectly passing arrays to the function. Fixed that in the original post. However, the problem still remains. PS: The program crashes as it waits for the input. It looks like an infinite loop problem too.

– Uriel Guzmán
Nov 25 '18 at 20:08







It seems I was incorrectly passing arrays to the function. Fixed that in the original post. However, the problem still remains. PS: The program crashes as it waits for the input. It looks like an infinite loop problem too.

– Uriel Guzmán
Nov 25 '18 at 20:08















You hit the core of the question. I tried gdb on my device, and found a stack smashing after return 0; of main. But I don't know why it is at this statement.

– Geno Chen
Nov 25 '18 at 20:12





You hit the core of the question. I tried gdb on my device, and found a stack smashing after return 0; of main. But I don't know why it is at this statement.

– Geno Chen
Nov 25 '18 at 20:12













Oh, for the original question's code, even string and string_copy are rewritten into some unexpected value...

– Geno Chen
Nov 25 '18 at 20:14





Oh, for the original question's code, even string and string_copy are rewritten into some unexpected value...

– Geno Chen
Nov 25 '18 at 20:14













0














I tried to understand your logic and it seems there is a problem in there:



Why are you passing string[50] to each function? I assume you would like to use the same string variable in every function, so, there's two points for you to check:




  1. You should ask for the user to enter the string value before the switch() statement - call capture() in the row before the switch() line, for example. Otherwise, the user could enter other menu options before entering the "capture" function, and, in this case the string will not exist yet, causing a segmentation error - if I'm not mistaken. (Have you tried it? Choosing option 3, for example, before choosing option 1? It must not work)


  2. To pass the "string" variable by parameter, use "string", not "string[50]".
    After the declaration (where "50" is the size of the string), the expression "string[50]" represents the 50th value of the string, which doesn't even exist, as pointed in David's answer.







share|improve this answer
























  • Yes. David was right about that one. Already corrected the string parameters in the original post a few minutes ago. (It's now passing string instead of &string[50]). The segmentation error disappeared after I corrected it, though. But the original problem of the question still remains. I also just did what you said in point 1. Allthough it didn't fix the problem. I will keep it like that because, as you said, it's better to have the string captured before anything else.

    – Uriel Guzmán
    Nov 25 '18 at 20:28













  • Have you checked issue number 1?

    – Ândrea Andrade
    Nov 25 '18 at 20:31











  • I also don't understand the line "scanf(" %[^n]s", string);" in function capture(). Have you tried using just "scanf("%50c", string)" ? %s reads any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence. From: cplusplus.com/reference/cstdio/scanf You make take a look there ...

    – Ândrea Andrade
    Nov 25 '18 at 20:31













  • Sorry, I made a typo. I meant I corrected issue 1 (and 2 too). scanf(" %[^n]s", string); is for accepting string with spaces, stopping until the newline character is encountered. I left a space at first, because the newline character of the option menu was messing with the scanf. Tried fgets() and even using getchar() to eat the newline character but they seem to have nothing to do with the original problem.

    – Uriel Guzmán
    Nov 25 '18 at 20:34













  • I see.. I'll need to leave right now, but I can try to help you later if the problem persists. I reccomended a link for you in the previous comment, hope it helps.. ': )

    – Ândrea Andrade
    Nov 25 '18 at 20:37
















0














I tried to understand your logic and it seems there is a problem in there:



Why are you passing string[50] to each function? I assume you would like to use the same string variable in every function, so, there's two points for you to check:




  1. You should ask for the user to enter the string value before the switch() statement - call capture() in the row before the switch() line, for example. Otherwise, the user could enter other menu options before entering the "capture" function, and, in this case the string will not exist yet, causing a segmentation error - if I'm not mistaken. (Have you tried it? Choosing option 3, for example, before choosing option 1? It must not work)


  2. To pass the "string" variable by parameter, use "string", not "string[50]".
    After the declaration (where "50" is the size of the string), the expression "string[50]" represents the 50th value of the string, which doesn't even exist, as pointed in David's answer.







share|improve this answer
























  • Yes. David was right about that one. Already corrected the string parameters in the original post a few minutes ago. (It's now passing string instead of &string[50]). The segmentation error disappeared after I corrected it, though. But the original problem of the question still remains. I also just did what you said in point 1. Allthough it didn't fix the problem. I will keep it like that because, as you said, it's better to have the string captured before anything else.

    – Uriel Guzmán
    Nov 25 '18 at 20:28













  • Have you checked issue number 1?

    – Ândrea Andrade
    Nov 25 '18 at 20:31











  • I also don't understand the line "scanf(" %[^n]s", string);" in function capture(). Have you tried using just "scanf("%50c", string)" ? %s reads any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence. From: cplusplus.com/reference/cstdio/scanf You make take a look there ...

    – Ândrea Andrade
    Nov 25 '18 at 20:31













  • Sorry, I made a typo. I meant I corrected issue 1 (and 2 too). scanf(" %[^n]s", string); is for accepting string with spaces, stopping until the newline character is encountered. I left a space at first, because the newline character of the option menu was messing with the scanf. Tried fgets() and even using getchar() to eat the newline character but they seem to have nothing to do with the original problem.

    – Uriel Guzmán
    Nov 25 '18 at 20:34













  • I see.. I'll need to leave right now, but I can try to help you later if the problem persists. I reccomended a link for you in the previous comment, hope it helps.. ': )

    – Ândrea Andrade
    Nov 25 '18 at 20:37














0












0








0







I tried to understand your logic and it seems there is a problem in there:



Why are you passing string[50] to each function? I assume you would like to use the same string variable in every function, so, there's two points for you to check:




  1. You should ask for the user to enter the string value before the switch() statement - call capture() in the row before the switch() line, for example. Otherwise, the user could enter other menu options before entering the "capture" function, and, in this case the string will not exist yet, causing a segmentation error - if I'm not mistaken. (Have you tried it? Choosing option 3, for example, before choosing option 1? It must not work)


  2. To pass the "string" variable by parameter, use "string", not "string[50]".
    After the declaration (where "50" is the size of the string), the expression "string[50]" represents the 50th value of the string, which doesn't even exist, as pointed in David's answer.







share|improve this answer













I tried to understand your logic and it seems there is a problem in there:



Why are you passing string[50] to each function? I assume you would like to use the same string variable in every function, so, there's two points for you to check:




  1. You should ask for the user to enter the string value before the switch() statement - call capture() in the row before the switch() line, for example. Otherwise, the user could enter other menu options before entering the "capture" function, and, in this case the string will not exist yet, causing a segmentation error - if I'm not mistaken. (Have you tried it? Choosing option 3, for example, before choosing option 1? It must not work)


  2. To pass the "string" variable by parameter, use "string", not "string[50]".
    After the declaration (where "50" is the size of the string), the expression "string[50]" represents the 50th value of the string, which doesn't even exist, as pointed in David's answer.








share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 25 '18 at 20:22









Ândrea AndradeÂndrea Andrade

11




11













  • Yes. David was right about that one. Already corrected the string parameters in the original post a few minutes ago. (It's now passing string instead of &string[50]). The segmentation error disappeared after I corrected it, though. But the original problem of the question still remains. I also just did what you said in point 1. Allthough it didn't fix the problem. I will keep it like that because, as you said, it's better to have the string captured before anything else.

    – Uriel Guzmán
    Nov 25 '18 at 20:28













  • Have you checked issue number 1?

    – Ândrea Andrade
    Nov 25 '18 at 20:31











  • I also don't understand the line "scanf(" %[^n]s", string);" in function capture(). Have you tried using just "scanf("%50c", string)" ? %s reads any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence. From: cplusplus.com/reference/cstdio/scanf You make take a look there ...

    – Ândrea Andrade
    Nov 25 '18 at 20:31













  • Sorry, I made a typo. I meant I corrected issue 1 (and 2 too). scanf(" %[^n]s", string); is for accepting string with spaces, stopping until the newline character is encountered. I left a space at first, because the newline character of the option menu was messing with the scanf. Tried fgets() and even using getchar() to eat the newline character but they seem to have nothing to do with the original problem.

    – Uriel Guzmán
    Nov 25 '18 at 20:34













  • I see.. I'll need to leave right now, but I can try to help you later if the problem persists. I reccomended a link for you in the previous comment, hope it helps.. ': )

    – Ândrea Andrade
    Nov 25 '18 at 20:37



















  • Yes. David was right about that one. Already corrected the string parameters in the original post a few minutes ago. (It's now passing string instead of &string[50]). The segmentation error disappeared after I corrected it, though. But the original problem of the question still remains. I also just did what you said in point 1. Allthough it didn't fix the problem. I will keep it like that because, as you said, it's better to have the string captured before anything else.

    – Uriel Guzmán
    Nov 25 '18 at 20:28













  • Have you checked issue number 1?

    – Ândrea Andrade
    Nov 25 '18 at 20:31











  • I also don't understand the line "scanf(" %[^n]s", string);" in function capture(). Have you tried using just "scanf("%50c", string)" ? %s reads any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence. From: cplusplus.com/reference/cstdio/scanf You make take a look there ...

    – Ândrea Andrade
    Nov 25 '18 at 20:31













  • Sorry, I made a typo. I meant I corrected issue 1 (and 2 too). scanf(" %[^n]s", string); is for accepting string with spaces, stopping until the newline character is encountered. I left a space at first, because the newline character of the option menu was messing with the scanf. Tried fgets() and even using getchar() to eat the newline character but they seem to have nothing to do with the original problem.

    – Uriel Guzmán
    Nov 25 '18 at 20:34













  • I see.. I'll need to leave right now, but I can try to help you later if the problem persists. I reccomended a link for you in the previous comment, hope it helps.. ': )

    – Ândrea Andrade
    Nov 25 '18 at 20:37

















Yes. David was right about that one. Already corrected the string parameters in the original post a few minutes ago. (It's now passing string instead of &string[50]). The segmentation error disappeared after I corrected it, though. But the original problem of the question still remains. I also just did what you said in point 1. Allthough it didn't fix the problem. I will keep it like that because, as you said, it's better to have the string captured before anything else.

– Uriel Guzmán
Nov 25 '18 at 20:28







Yes. David was right about that one. Already corrected the string parameters in the original post a few minutes ago. (It's now passing string instead of &string[50]). The segmentation error disappeared after I corrected it, though. But the original problem of the question still remains. I also just did what you said in point 1. Allthough it didn't fix the problem. I will keep it like that because, as you said, it's better to have the string captured before anything else.

– Uriel Guzmán
Nov 25 '18 at 20:28















Have you checked issue number 1?

– Ândrea Andrade
Nov 25 '18 at 20:31





Have you checked issue number 1?

– Ândrea Andrade
Nov 25 '18 at 20:31













I also don't understand the line "scanf(" %[^n]s", string);" in function capture(). Have you tried using just "scanf("%50c", string)" ? %s reads any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence. From: cplusplus.com/reference/cstdio/scanf You make take a look there ...

– Ândrea Andrade
Nov 25 '18 at 20:31







I also don't understand the line "scanf(" %[^n]s", string);" in function capture(). Have you tried using just "scanf("%50c", string)" ? %s reads any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence. From: cplusplus.com/reference/cstdio/scanf You make take a look there ...

– Ândrea Andrade
Nov 25 '18 at 20:31















Sorry, I made a typo. I meant I corrected issue 1 (and 2 too). scanf(" %[^n]s", string); is for accepting string with spaces, stopping until the newline character is encountered. I left a space at first, because the newline character of the option menu was messing with the scanf. Tried fgets() and even using getchar() to eat the newline character but they seem to have nothing to do with the original problem.

– Uriel Guzmán
Nov 25 '18 at 20:34







Sorry, I made a typo. I meant I corrected issue 1 (and 2 too). scanf(" %[^n]s", string); is for accepting string with spaces, stopping until the newline character is encountered. I left a space at first, because the newline character of the option menu was messing with the scanf. Tried fgets() and even using getchar() to eat the newline character but they seem to have nothing to do with the original problem.

– Uriel Guzmán
Nov 25 '18 at 20:34















I see.. I'll need to leave right now, but I can try to help you later if the problem persists. I reccomended a link for you in the previous comment, hope it helps.. ': )

– Ândrea Andrade
Nov 25 '18 at 20:37





I see.. I'll need to leave right now, but I can try to help you later if the problem persists. I reccomended a link for you in the previous comment, hope it helps.. ': )

– Ândrea Andrade
Nov 25 '18 at 20:37


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471243%2fscanf-keeps-waiting-for-input-after-a-string-with-spaces-is-entered%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

TypeError: fit_transform() missing 1 required positional argument: 'X'