如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++

How to read in individual characters and output when two-character-sequence is inputted? using while loop and C++

本文关键字:字符 使用 输出 while C++ 循环 单个 读取 何读取 输入 两个      更新时间:2023-10-16

我正在尝试编写一个程序,该程序以单个字符读取,并在门打开的两个字符序列"cs"时提示用户。我被困在完全读取字符串后存储当前值的位置或方式并输出响应。

从记事本读取数据:


CS iMacsMajor
CSS
AB
DECD

期望输出:

CS 开门

iMacS主要开门

CSS 开门 AB 关门
关门

到目前为止编写的代码:

文件:开门.cpp

#include <conio.h>
#include <fstream>// requires for external file streams 
#include <iostream>
using namespace std; 
// Associating program identifiers with external file names 
#define in_file  "data.txt"
#define out_file "resline.txt" 
void main()
{
const char nwln = 'n';  // print a new line 
ifstream ins;  // associates ins as an input stream  ofstream outs; 
ofstream outs; // associates outs as an output stream 
int  door = 0;  
char  current, previous = ' ', password;
ins.open(in_file);
outs.open(out_file);   
// Repeat processing until end of file is reached 
ins.get(current);  
while (!ins.eof())  
{     
cout << current ;
// read a character   
while (current != 'n')  
{    
ins.get(current);       
cout << current ;  
}
} 
_getch();  
ins.close();    // closing input file 
outs.close();   // closing output file
}  // end main 

您所要做的就是检查给定字符串中是否有c,如果您发现s之后您找到了c,那么您就有了答案。

另外,您可能知道,字符串本质上是一个char数组。

在代码中,此算法可能如下所示:

std::string s = "abcdcsg";
// string is essentially a char array to begin with
for (int i = 0; i< s.length(); i++)
{
if (s[i] == 'c')
{
i+=1;
if(s[i]=='s'){
//found
break;
}
}
}

这是我的代码。 对于其他挣扎的人。

//file: dooropen.cpp
#include <conio.h>
#include <iostream>
#include <fstream>// requires for external file streams
using namespace std; // Associating program identifiers with external file names
#define in_file  "data.txt" 
#define out_file "resline.txt"
void main()
{
const char nwln = 'n';  // print a new line
ifstream ins;  // associates ins as an input stream  
ofstream outs; // associates outs as an output stream 
int count = 0;
int  door = 0;
int isc = 0;
char  current, previous = ' ';
ins.open(in_file);
outs.open(out_file);    // Repeat processing until end of file is reached 
ins.get(current);
while (!ins.eof())
{
cout << current;// read a character   
while (current != 'n')
{
if (current == 'c')
{
isc = count;
}
if (current == 's')
{
if (count == isc + 1)
{
door = 1;
}
}
ins.get(current);
cout << current;
count++;
}
if (door == 1)
{
cout << ". . . . . . . . . . . . . . . . Door open n";
}
else
{
cout << ". . . . . . . . . . . . . . . . Door closed n";
}
door = 0;
isc = 0;
ins.get(current);
}
_getch();
ins.close();    // closing input file 
outs.close();   // closing output file
}  // end main