有以下四种方法
方法一
#include
#include
#include
using namespace std;
int main()
{
ifstream ifs("test.cpp"); // 改成你要打开的文件
streambuf* old_buffer = cin.rdbuf(ifs.rdbuf());
string read;
while(cin >> read) // 逐词读取方法一
cout << read;
cin.rdbuf(old_buffer); // 修复buffer
}
方法二
#include
#include
using namespace std;
int main()
{
ifstream ifs("test.cpp"); // 改成你要打开的文件
ifs.unsetf(ios_base::skipws);
char c;
while(ifs.get(c)) // 逐词读取方法二
{
if(c == ' ')
continue;
else
cout.put(c);
}
}
方法三
#include
#include
#include
using namespace std;
int main()
{
ifstream ifs("test.cpp"); // 改成你要打开的文件
string read;
while(getline(ifs, read, ' ')) // 逐词读取方法三
{
cout << read << endl;
}
}
方法四
#include
#include
using namespace std;
int main()
{
ifstream ifs("test.cpp"); // 改成你要打开的文件
char buffer[256];
while(ifs.getline(buffer, 256, ' ')) // 逐词读取方法四
{
cout << buffer;
}
}
建立一个字符数组就可以了,比如char a[]="中文";一个汉字占两个字节,所以用一个字节的char类型无法存储中文
一个汉字是占两个字节的
#include
void main()
{
char x[2];
scanf("%c%c",&x[1],&x[2]);
printf("x=%c%c",x[1],x[2]);
}
中文只能以字符串形式读入,比如
char s[25];
scanf("%s",s);