visual studio 2013 - user initiated looping in c++ -
visual studio 2013 - user initiated looping in c++ -
this question has reply here:
how scanf single char in c 6 answersi write programme takes input user , calculates triangular number. there should alternative inquire user if wants take input or exit , needs done using while or do...while. have next code written doesn't intended:
#include <stdio.h> int main(void) { int n, number, triangularnumber; char s = 'y'; while (s == 'y') { printf("what triangular number want? "); scanf("%i", &number); triangularnumber = 0; (n = 1; n <= number; ++n) triangularnumber += n; printf("triangular number %i %i\n\n", number, triangularnumber); printf("do want continue?\n"); scanf("%c", &s); } homecoming 0; } the above code 1 time after exits. how can create run loop 1 time again based on input give? in advance.
two problems: first of there difference between little , capital letters, 'y' != 'y'.
the sec problem, , seeing here, first scanf read number, leaves newline in input buffer. sec scanf phone call reads newline , writes variable s.
the first problem can solved making sure contents of variable s capital letter, using toupper:
while (toupper(s) == 'y') { ... } the sec problem can fixed asking scanf read , discard leading whitespace when getting character, done adding space before format code:
scanf(" %c", &s); // ^ // | // note space here c++ visual-studio-2013
Comments
Post a Comment