이 포럼과 튜토리얼을 탐색 할 때 적절한 형식 (내 생각)으로 조정했지만 단 하나의 항목 만 빠져있는 동안이 주제는 관련 주제라고 생각합니다. for 루프를 사용하여 정수를 취하고 정수에서 c-string 값을 할당하려면 어떻게해야합니까?for 루프를 사용한 C 문자열 할당
저는 지금 바이너리 부분의 정수에 초점을 맞추고 있습니다. 제 숫자 조작은 확실합니다. 그러나 우리 교수는 이진 값을 C 문자열에 할당해야한다고했습니다. 그리고 이것을 시도하고 있는데 const char과 char *을 컴파일러를 통해 사용하고 있다고합니다. 어떻게 이런 일이 일어나고 있는지, 또는 어떻게 막을 지 모르겠습니다.
가 여기 내 소스 코드입니다 :
//sample integer to binary
#include <iomanip>
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main()
{
int num; //the number a user enters
int rem; //the remainder, the 1 and 0 of the binary number
int x; //a variable to store the number after division
char binary[10]; //c-string initialized to 10, perhaps that is too many.
cout << "Enter a number: ";
cin >> num;
for (int i = 0; i < 10; i++)
{
x = num/2;
cout << x << endl; //this shows that the code is working
rem = num % 2;
cout << num << endl; //this also shows the code is working
char r = (char)rem; //These two lines of code are
strcpy(binary[i], r); //preventing compilation
cout << binary[i] << endl; // this is diagnostic
num = x;
}
cout << "The number " << num << " is " << binary[5] << " in binary.\n";
return 0;
}
감사 당신이, 내가이 일을 (거의) 만들 수있었습니다. 나는 예기치 않은 행동을하고 있는데 배열을 초기화하는 것이 얼마나 큰지 잘 모르겠다.별로 중요하지 않다고 생각하지만, 그레이더가 얼마나 큰 숫자를 사용하는지 정확히 알지 못한다. 테스트 할.
어쨌든, 여기에 새로운 코드입니다 : 여기
#include <iomanip>
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main()
{
int num; //the number a user enters
int rem; //the remainder, the 1 and 0 of the binary number
int x; //a variable to store the number after division
char binary[5] = {'0', '\0'}; //c-string initialized to 10, perhaps that is too many.
cout << "Enter a number: ";
cin >> num;
for (int i = 0; i < 10; i++)
{
x = num/2;
//cout << x << endl; //this shows that the code is working
rem = num % 2;
//cout << num << endl; //also shows the code is working
binary[i] = '0' + rem; //not sure what this is doing, but it works.
//cout << binary[i] << endl; // this is diagnostic
num = x;
}
cout << "The number " << num << " is " << binary << " in binary.\n";
return 0;
}
그리고 출력입니다 :
는 번호를 입력 : 5 수 0 이진 1010000000 #입니다.
0과 # 기호없이 숫자, 초기 숫자 및 말하기 101을 나타내야합니다.
당신은 C 스타일 문자열을 사용하는 이유라도? – clcto
배열을 사용해 보았지만 이상한 숫자가 나왔습니다. 내가 설정 한 방식대로하는 것은 진단 코드가 보여주는 것만 1과 0으로 제공해야합니다. – Tamra
그리고 난 정말 선택의 여지가 없어! 그것은 과제의 일부입니다. :/우리가 다루는 새로운 주제입니다. C- 문자열. – Tamra