While I've seen some people answer this for Python, I don't know how to do so in C++. Bear in mind, I'm still learning.
As the title should tell you, I'm trying to define multiple variables in a C++ program via a while loop. Specifically, I am trying to make it so it will read through the first 8 characters of a string, and then assign them to their dedicated char values of c1, c2, c3, c4, c5, c6, c7, and c8. However, I can't figure out an easy way to make it do this.
For an example, it should see the string "FAR OUT!" and print the following characters to each c1-8 variable:
- F
- A
- R
- (space)
- O
- U
- T
- !
The most recent attempt seems to believe I am referring to a variable called "c", and not consider the fact I'm telling it to take the value of the variable check, add 1 to it, and then add that number to the end of c, and then take the variable that is that output.
#include <iostream>
#include <string>
using namespace std;
int main()
{
// varaible declaration(s)
char c1;
char c2;
char c3;
char c4;
char c5;
char c6;
char c7;
char c8;
string phonenumber;
int check = 0;
// accept user input
cout << "Phone number in letters: ";
cin >> phonenumber;
// convert string to char
while(check < 8)
{
phonenumber[check] = c(check + 1);
check = check + 1;
}
// start while loop
// program logic and output
cout << endl << c1 << c2 << c3 << c4 << c5 << c6 << c7 << c8 << endl;
}
Why don't you just use a char array ?
#include <array>
...
// instead of c1, c2, ...
std::array<char, 8> c;
// later
while (condition) {
// read or set here, whatever you need
c[check] = some_value;
...
}
A while
loop won't work for this. The names of variables are determined when the code is compiled; you can't make variable names on the fly when the program is running.
So don't use the loop. After you've read phonenumber
, copy the values into the appropriate variables:
c1 = phonenumber[0];
c2 = phonenumber[1];
and so on. Of course, if phonenumber
has fewer than 8 characters in it, you've got a problem...
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.