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
2 this day I wanna
3 help
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?
We can make scanf() to read a new line by using an extra \n, i.e., scanf(“%d\n”, &x) . In fact scanf(“%d “, &x) also works (Note the extra space). We can add a getchar() after scanf() to read an extra newline.
Simply comparing to '\n' should solve your problem; depending on what you consider to be a newline character, you might also want to check for '\r' (carriage return).
On the other hand (as Paul Griffiths' answer points out), "\n" (with double quotes rather than single quotes) is a string literal that represents a string value. That string consists of two characters, a single '\n' newline character and a '\0' null character that marks the end of the string.
Use std::getline
to read line by line. Put in a std::vector
. Print the vector indexes (plus one) and the strings from the vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With