C 读取输入,直到线char数组的结束

c++ read input until the end of line char array

本文关键字:char 数组 结束 读取 输入      更新时间:2023-10-16

我正在尝试使我的代码起作用,实际上它可以正常工作,但效果不佳。" Enter"出现后,代码停止。我想使我的代码正常工作,直到用户输入文件结束为止。

 #include<iostream>
using namespace std;
int main(){
    char input[2000];

    cin.getline(input, sizeof(input));
    int lol = strlen(input);
    int boing = 0;
    for (int p = 0; p < lol; p++)
    {
        if (input[p] == '"')
        {
            boing++;
            if (boing % 2 == 1)
            {
                cout << '`'<<'`';
            }
            if (boing % 2 == 0)
            {
                cout << '''<<''';
            }
        }
        else
            cout << input[p];
    }
    system("pause");
}

如果我们输入输入这些单词

在"我的up"严格"记住"中分支。 歌曲,但酋长有火腿寡妇唐斯。天才左右的虚荣心不能。 ''''``大型do尝试了 goi"''''ng''关于水的延迟。 不信任的津贴会为知识急切的保证增加。 我们"""如果痛苦痛苦";`392view"她的时间很长时间。领导的年轻同性恋现在都会说"。

我的输出变为

''my up strictly中分支。请记住。''

,但应该是

''my up strictly中分支了。``歌曲,但酋长有 火腿寡妇唐斯。天才左右的虚荣心不能。````````大事尝试 goi'''ng'' about water defer by. Silent'她希望的儿子男人 母亲。不信任津贴做知识急切的保证 补充。我们 ''''减少偏好thoroughly if. ''Joy deal pain ';`392view她的时间很多。领导的年轻同性恋现在会说。''

getline将输入,直到按下" Enter"按钮。您的代码在我的机器上运行良好。只需添加string.h标头文件:

#include<string.h>

这是针对strlen函数的。

对于此代码,您需要两个标头文件

#include <string.h>
#include <stdlib.h>

您的完整代码将为

#include<iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main()
{
    char input[2000];

    cin.getline(input, sizeof(input));
    int lol = strlen(input);
    int boing = 0;
    for (int p = 0; p < lol; p++)
    {
        if (input[p] == '"')
       {
           boing++;
           if (boing % 2 == 1)
           {
               cout << '`'<<'`';
           }
           if (boing % 2 == 0)
           {
              cout << '''<<''';
           }
      }
      else
        cout << input[p];
   }
   cout<<endl;   //this line is for making ur code look nice
   system("pause");
}

,但我个人建议您将C 字符串类用于字符串处理它很容易且非常有用

使用字符串类,您的代码将为

#include<iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
   string input;
   getline(cin,input);
   int lol = input.size();
   int boing = 0;
   for (int p = 0; p < lol; p++)
   {
      if (input[p] == '"')
      {
          boing++;
          if (boing % 2 == 1)
          {
             cout << '`'<<'`';
          }
          if (boing % 2 == 0)
          {
              cout << '''<<''';
          }
      }
      else
          cout << input[p];
   }
   cout<<endl;
   system("pause");
   return 0;
}

快乐编码

您需要以某种形式的循环包装getline。现在,您将获得1行,然后操纵input然后退出。现在,您将其从用户中拉入,因此您需要寻找终结者。