[英]How to detect a newline in string input in C++
I want to count each newline 我想计算每个换行符
If the input like this: 如果输入如下:
Hi moon 嗨月亮
this day I wanna 这一天我想
help 救命
Should be the output like this: 应该是这样的输出:
1 Hi moon 1嗨月亮
2 this day I wanna 2这天我想
3 help 3帮助
I write this code: 我写这段代码:
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;
}
and I was to try : 我试着尝试:
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];
}
Can anyone tell to me how to detect a newline in string input and print it? 任何人都可以告诉我如何检测字符串输入中的换行并打印它?
Use std::getline
to read line by line. 使用std::getline
逐行读取。 Put in a std::vector
. 放入std::vector
。 Print the vector indexes (plus one) and the strings from the vector. 打印矢量索引(加一)和矢量中的字符串。
I would like to start by defining what a new line is. 我想首先定义新行是什么。 On windows, it is a sequence of two characters \\r\\n
, on UNIX it is simply \\n
. 在Windows上,它是一个由两个字符组成的序列\\r\\n
,在UNIX上它只是\\n
。 Treating new line as '\\n' will suffice in your case since your dealing with text input (not binary, as C will handle the translation). 将新行作为'\\ n'处理就足够了,因为你处理文本输入(不是二进制,因为C将处理翻译)。
I suggest you split your problem into two sub-problems: 我建议你将问题分成两个子问题:
I would do something like this: 我会做这样的事情:
#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] = '\0';
(*pos)++;
return temp;
}
int main() {
char str[] = "hello\nworld!\ntrue";
int pos = 0;
while(pos < strlen(str)){
cout << nextLine(str, &pos) << "\n";
}
return 0;
}
Hope that helps! 希望有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.