簡體   English   中英

與字符串文字C ++的比較

[英]Comparison with string literal C++

我正在為一個程序編寫函數,該程序允許學生復制模板文本文件。 此功能檢查用戶的輸入,以查看其類是否允許使用所需的模板。

我在第21和25行上收到錯誤消息“與字符串文字進行比較會導致未指定的行為”。我完成了“ cout << name”操作,以驗證變量是否正確存儲,所以我知道這不是問題所在。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

//TEMPLATE CHECK
//First you check to see if the student is allowed to use the template
int templateCheck()
{
    //Declare file name variable
    char name[256];

    //Prompt for user input
    cout << "Enter file name: ";

    //Cin user input
    cin >> name;

    //Begin check
    //CS221 is the first template you can't use
    if(name == "/home/cs221Temp.txt")
        cout << "You are not allowed to use CS221 templates./n";

        //CS 321 is the other template you can't use
        else if (name == "/home/cs321Temp.txt")
        cout << "You are not allowed to use CS321 templates./n";

        //Any others are okay (I commented these out since I'm just working on this function by itself)
        //else 
        //copyTemplate();

        return 0;
}

這個說法

if(name == "/home/cs221Temp.txt")

比較指針是否相等(這不太可能),而不是其內容。
你真正想要的是

if(strncmp(name,"/home/cs221Temp.txt",256) == 0)

要么

std::string name;

在你的職能。

您不能通過==來比較兩個C樣式的字符串。 (C樣式的字符串文字只為您提供指向RAM中字符序列中第一個字符的指針,以0值字符結尾,因此您將比較地址而不是字符串)。

您要使用的是stdlibstrcmp函數。

但是,您正在編寫C ++,而不是C。

因此,我建議使用string類,該類具有重載的==運算符,因此您可以

if (string1 == string2)

在C / C ++中(不同於像JavaScript這樣的“相似”語言),當對“字符串”使用== ,您正在比較指針。 如果要比較字符串的內容,則必須使用為此目的而設計的函數。 就像標准C庫中的strcmp()一樣

暫無
暫無

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

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