簡體   English   中英

意外的cin行為

[英]Unexpected cin behavior

我正在編寫一個函數int count_words(string str) ,該函數返回int count_words(string str)中所有單詞的計數。

問題是無論輸入什么,結果都是1。有人可以幫忙嗎?

#include <iostream>
#include <string>

using namespace std;

int count_words(string str)
{
    int i,j;
    j = 1;
    int l = str.length();
    for(i = 0; i < l; i++)
    {
        string c = str.substr(i,1);
        if(c == " ")
        {
            j++;
        }
    }
    cout << "The total word in the string: " << j << endl;
    return j;
}


int main()
{
    string str;
    cout << "Please enter a string: ";
    cin >> str;
    int result = count_words(str);
    return 0;
}

如果字符串中包含空格,則應使用cin.getline ,因為將>>運算符與cin只能讀取下一個空格

看到std :: cin輸入有空格嗎?

考慮遍歷字符串:

auto cstyle= str.c_str();
for (int i = 0; i < str.length(); ++i)
{
  if (cstyle[i]==' ')//assumes words are delimited by a single space
  {
    j++;
  }
}

您應該使用: cin.getline ,例如:

int main()
{
    cout << "Please enter a string: ";
    unsigned size=10;
    char*chr=new char[size];
    cin.getline(chr,size);
    string str(chr);
    //cin >> str;
    int result = count_words(str);
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM