【问题标题】:How to read spaces as characters in C++如何在 C++ 中将空格读取为字符
【发布时间】:2018-02-02 09:42:21
【问题描述】:

我想从 .txt 文件中读取所有字符,但我的程序没有读取空格,我不知道为什么。 我也想用开关测试所有字符,但空格不会被检测为字符。 如何解决这个问题?

PS:我想不用getline来解决这个问题

这是我的代码:

#include <iostream>
#include <fstream>
#define InFile "intra.txt"
#define OutFile "raspuns.txt"
using namespace std;
ifstream fin(InFile);
ofstream fout(OutFile);

int main()
{
long int i,valori[100],aux, contor;
char a[10000];


i=0;
contor = -1;
do
{
 contor++;
 i++;
 fin>>a[i];
 cout<<a[i]<<"\n";
 switch(a[i]){
 ...
 }

【问题讨论】:

  • fin &gt;&gt; std::noskipws; 一次,就在你打开它之后。
  • 非常感谢您的回答!向您致以最诚挚的问候!
  • 如果您使用现代 C++ 编写代码,请将 #define InFile "intra.txt" 更改为 static constexpr auto InFile = "intra.txt"。你未来的同事会很感激的。

标签: c++ char switch-statement do-while file-read


【解决方案1】:

这样试试

std::ifstream file("../../temp.txt");
if(!file)return 0;
std::string line;

while (std::getline(file, line, '\0')){
    for(char ascii : line){
        std::cout<<(int)ascii << " ";
    }
}
system("pause");
return 0;

【讨论】:

    猜你喜欢
    • 2011-04-30
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多