如何在C++中检测字符串输入中的换行符

How to detect a newline in string input in C++

本文关键字:输入 换行符 字符串 检测 C++      更新时间:2023-10-16

我想计算每个换行
符如果输入如下:

嗨月亮
,这天我想
帮忙

应该是这样的输出:

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 将处理翻译(。

我建议你将问题分为两个子问题:

  1. 存储一行
  2. 在有更多行时进行迭代

我会做这样的事情:

#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;
}

希望对您有所帮助!