如何在C++中检测字符串输入中的换行符
How to detect a newline in string input in C++
我想计算每个换行
符如果输入如下:
嗨月亮
,这天我想
帮忙
应该是这样的输出:
1 嗨月
亮 2 这天我想
3 帮助
我写了这段代码:
int main() {
string str; int c = 0;
cin >> str;
int j = 0;
string t[200];
while (str != ";")
{
t[j] = str;
cin >> str;
}
for (int i = 0; i < j;i++){
cout << c << " " << t[j];
if (t[j] == "n") c++;
}
system("Pause");
return 0;
}
我要尝试:
int c[100];
cin >> str;
int j = 0;
string t[200];
while (str != ";")
{
string temp;
t[j] = str;
temp = t[j];
if (temp.find("n"))
c[j] += 1;
cin >> str;
}
for (int i = 0; i < j;i++){
cout << c[i] << " " << t[j];
}
谁能告诉我如何检测字符串输入中的换行符并打印出来?
使用 std::getline
逐行阅读。放入std::vector
.打印矢量索引(加一(和矢量中的字符串。
我想
从定义新行开始。在Windows上,它是一个由两个字符组成的序列rn
,在UNIX上,它只是n
。将新行视为""就足够了,因为您处理文本输入(不是二进制,因为 C 将处理翻译(。
我建议你将问题分为两个子问题:
- 存储一行
- 在有更多行时进行迭代
我会做这样的事情:
#include <iostream>
#include <cstring>
using namespace std;
char* nextLine(char* input, int* pos) {
char* temp = new char[200];
int lpos = 0; // local pos
while(input[*pos] != 'n') {
temp[lpos++] = input[(*pos)++];
}
temp[*pos] = ' ';
(*pos)++;
return temp;
}
int main() {
char str[] = "hellonworld!ntrue";
int pos = 0;
while(pos < strlen(str)){
cout << nextLine(str, &pos) << "n";
}
return 0;
}
希望对您有所帮助!
相关文章:
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- 如何在出现换行符之前将多个整数作为输入?
- 在字符串中输入换行符
- 使用 fgets() 从键盘读取时从以前的输入读取换行符
- 使用 getline 忽略用户输入中的制表符和换行符
- 如何在C++中检测字符串输入中的换行符
- 在C++中输入时未检测到换行符
- 如果在循环中给cin一个意外的输入,则会自动输入C++换行符作为输入
- 读取整数对,直到文本输入文件中的换行符
- 输入整数直到 C/C++ 中的换行符
- 如何将换行符按钮更改为空格以完成从输入流的读取
- 你能定制一个输入的换行符(C++)吗
- C++清除输入缓冲区(最后没有换行符)
- 使用 getchar() 输入字符的最有效方法,就像 cin 中没有换行符和空格字符一样C++
- 为什么 fstream::tellg() 返回值会因输入文本文件中的换行符数而增大,当文件针对 Windows (r
- 清除包括换行符在内的输入缓冲区
- C++丢弃输入缓冲区问题中剩下的换行符
- c++getline似乎无法识别通过管道传输到stdin的输入中的换行符
- "No newline at end of file"警告,即使在输入换行符后
- 如何在c++中输入换行符