简体   繁体   中英

append an integer variable to char variable in C++

I'm new in C++, I have a small project, I should get 10 numbers from user and then show in result.

so I wrote this code :

#include<stdio.h>
int main() {
    int counter=1,
        allNumbers;
    float score;
    while(counter <= 10) {
        scanf("%f",&score);
        counter++;
    }

    printf("Your entered numbers are : %s\n",allNumber);
}

for example user enter 2 3 80 50 ... and I want show 2,3,80,50,... in result.

But I don't know what should I do !

I do not know what book you are using, but the authors appear to teach you C before going into the C++ land. Without discussing their motives, I'll write an answer to be similar to your style of code before discussing an ideal C++ solution.

  • You need an array to store your numbers: double score[10]
  • Array are indexed starting from zero, so change counter to start at zero and go to nine (instead of starting at one and going to ten, like you have now)
  • Since score is an array, use &score[count] in the call of scanf
  • To print ten numbers you need a loop as well. You need a flag that tells you whether or not you need a comma after the number that you print. Add a printf("\\n") after the loop.

As far as an "ideal" C++ solution goes, it should look close to this one:

istream_iterator<double> eos;
istream_iterator<double> iit(cin); 
vector<double> score;
copy(iit, eos, back_inserter(score));
ostream_iterator<double> oit (cout, ", ");
copy(score.begin(), score.end(), oit);

However, discussing it would remain hard until you study the C++ standard library and its use of iterators.

You can do it by declaring an array of ten numbers. your code goes here:

#include <stdio.h>
int main() {
int counter=0;
float allNumbers[10];
while(counter < 10) {
    scanf("%f",&allNumbers[counter]);
    counter++;
        }

printf("Your entered numbers are : \n");
counter=0;
while(counter < 10) {
    printf("%f , ",allNumbers[counter]);
    counter++;
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM