4) 用c++编程;输入一字符,将字符的ASCII码值用二进制形式输出;

如题所述

的读入还是有一定的问题的,我把它改成如此:
#include <iostream>
#include <fstream>
#include <cstring> //为了求字符串的长度
using namespace std;

int main()
{
ofstream output;
output.open("output.txt"); //新建一个output.txt
char a[50],b[50];
cout << "请输入一串您想储存到计算机上的字符,并以“#”号键结束:"<<endl;
cin >> b; //直接读入B后再处理,以免逐个读入读乱掉
b[strlen(b)-1] = '\0'; //strlen是一个函数,包含在<cstring>里,意在求出b字符串的长度。
output << b;
cout<<"您所输入的字符串:“"<<b<<"”已储存到计算机中。"<<endl;
output.close(); //在前面我写的程序中,我没有注意到这一点,要关闭文件。关闭文件就用fstream对象函数表示,close()
}

从output.txt读入就需要用到我们C++的一个类ifstream。它专门用来从文件当中读入数据的。其用法为:ifstream in ( "xxx.txt" ); 这里in是一个标识符,可以是任何合法的名称,xxx.txt是文件名称。这样,我们就可以用这个对象去完成你的任务了。第二次审查后,我的程序简略了很多。
ifstream in("output.txt");
in >> a;
for ( int i = 0; i < strlen(a); i++ ) {
if ( a[i] >= 'a' && a[i] <= 'z' ) cout << static_cast<char>(a[i]-32); //如果是小写就转换。在你提出的另外一个问题中,有网友指出这样转换会令人迷惑。static_cast<type>(a)是将a转换为type类型,所以建议你用这个格式,就不容易乱了。
else cout << a[i];
}
由于在for循环当中已经逐字从文件读入转换并输出,这里并不需要做任何事情。整个文件如下:

//change_from_file.cpp
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main()
{
ofstream output;
output.open("output.txt");output.txt
char a[50],b[50];
cout << "请输入一串您想储存到计算机上的字符,并以“#”号键结束:"<<endl;
cin >> b;
b[strlen(b)-1] = '\0';
output << b;
cout<<"您所输入的字符串:“"<<b<<"”已储存到计算机中。"<<endl;
output.close();
ifstream in("g:/output.txt");
in >> a;
for ( int i = 0; i < strlen(a); i++ ) {
if ( a[i] >= 'a' && a[i] <= 'z' ) cout << static_cast<char>(a[i]-32);
else cout << a[i];
}
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-04-12
给你一个最简单的答案:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
char input;
char str[10];
printf("请输入您要转换的字符:\n");
scanf("%c",&input);
itoa(input,str,2);
printf( "%c 转换为二进制为:%s \n",input,str);
}

首先是输入一个字符,然后调用itoa()库函数对输入的字符进行转换,变成二进制数的字符串存到str数组中,再输出
相似回答